赞
踩
首先在 Nuget 包管理器中,安装 itext7
和 itext7.font-asian
。
如果不安装 itext7.font-asian
PDF 文件中有非Unicode编码的字符,将会抛出运行时异常:
iText.IO.Exceptions.IOException:找不到 CMap iText.IO.Font.Cmap.UniGB-UTF16-H
安装好了这两个组件之后,使用以下代码,从PDF文件中提取出所有的文本。
功能封装:
public class IText7Helper { public static string ExtractText(string pdfFilePath) { //创建一个PdfReader对象,用来读取pdf文件 PdfReader pdfReader = new PdfReader(pdfFilePath); //创建一个PdfDocument对象,用于操作pdf文档 PdfDocument pdfDocument = new PdfDocument(pdfReader); //创建一个StringBuilder对象,来存储提取的文本 StringBuilder textBuilder = new StringBuilder(); //获取pdf文档的总页数 int pageCount = pdfDocument.GetNumberOfPages(); //遍历每一页 for (int i = 1; i <= pageCount; i++) { //获取当前页的PdfPage对象 PdfPage pdfPage = pdfDocument.GetPage(i); //创建一个ITextExtractionStrategy对象,用于指定提取文本的策略 ITextExtractionStrategy strategy = new LocationTextExtractionStrategy(); //使用PdfTextExtractor类的GetTextFromPage方法,根据指定的策略提取当前页的文本 string pageText = PdfTextExtractor.GetTextFromPage(pdfPage, strategy); //将提取的文本追加到StringBuilder对象中 textBuilder.Append(pageText); } //关闭PdfDocument对象 pdfDocument.Close(); //返回StringBuilder对象中的字符串 return textBuilder.ToString(); } }
调用方法:
string text = IText7Helper.ExtractText("test.pdf");
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。