使用C#实现读取PDF中所有文本内容
更新时间:2024年02月02日 11:08:37 作者:搬砖的诗人Z
这篇文章主要为大家详细介绍了如何使用C#实现读取PDF中所有文本内容,文中的示例代码简洁易懂,具有一定的学习价值,有需要的小伙伴可以了解下
先安装如下包

实现代码
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ReadPdfText
{
class Program
{
static void Main(string[] args)
{
string path = "0017_审判流程管理信息表2.pdf";
var text = ReadPFD2(path);
Console.WriteLine(text);
Console.ReadKey();
}
public static string OnCreated(string filepath)
{
try
{
string pdffilename = filepath;
PdfReader pdfReader = new PdfReader(pdffilename);
int numberOfPages = pdfReader.NumberOfPages;
string text = string.Empty;
for (int i = 1; i <= numberOfPages; ++i)
{
iTextSharp.text.pdf.parser.ITextExtractionStrategy strategy = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
text += iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(pdfReader, i, strategy);
}
pdfReader.Close();
return text;
}
catch (Exception ex)
{
throw ex;
//StreamWriter wlog = File.AppendText(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\mylog.log");
//wlog.WriteLine("出错文件:" + ex.FullPath + "原因:" + ex.ToString());
//wlog.Flush();
//wlog.Close(); return null;
}
}
public static string ReadPFD2(string path)
{
// string path = path;// @"D:\ydfile\d4bab8ff-26ff-4ddf-a602-872f6988db86_.pdf";
string text = string.Empty;
try
{
string pdffilename = path;
StringBuilder buffer = new StringBuilder();
//Create a pdf document.
using (Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument())
{
// Load the PDF Document
doc.LoadFromFile(pdffilename);
// String for hold the extracted text
foreach (Spire.Pdf.PdfPageBase page in doc.Pages)
{
buffer.Append(page.ExtractText());
}
doc.Close();
}
//save text
text = buffer.ToString();
return text;
}
catch (Exception ex)
{
//DHC.EAS.Common.LogInfo.Debug("读取PDF文件返回=" + text);
//DHC.EAS.Common.LogInfo.Debug("读取PDF文件错误", ex);
return null;
}
}
}
}
到此这篇关于使用C#实现读取PDF中所有文本内容的文章就介绍到这了,更多相关C#读取PDF内容内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
C# Dynamic关键字之:dynamic为什么比反射快的详解
本篇文章是对C#中dynamic为什么比反射快进行了详细的分析介绍,需要的朋友参考下2013-05-05
C# string转换为几种不同编码的Byte[]的问题解读
这篇文章主要介绍了C# string转换为几种不同编码的Byte[]的问题解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-02-02
HttpWebRequest出错.Section=ResponseHeader Detail=CR
HttpWebRequest出错.Section=ResponseHeader Detail=CR...2007-03-03
C#中使用async和await实现异步Udp通讯的示例代码
本文主要介绍了C#中使用async和await实现异步Udp通讯的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-07-07


最新评论