使用C#實現(xiàn)讀取PDF中所有文本內(nèi)容
更新時間:2024年02月02日 11:08:37 作者:搬磚的詩人Z
這篇文章主要為大家詳細介紹了如何使用C#實現(xiàn)讀取PDF中所有文本內(nèi)容,文中的示例代碼簡潔易懂,具有一定的學(xué)習(xí)價值,有需要的小伙伴可以了解下
先安裝如下包

實現(xiàn)代碼
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;
}
}
}
}
到此這篇關(guān)于使用C#實現(xiàn)讀取PDF中所有文本內(nèi)容的文章就介紹到這了,更多相關(guān)C#讀取PDF內(nèi)容內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入c# 類和結(jié)構(gòu)的區(qū)別總結(jié)詳解
本篇文章是對c#中類和結(jié)構(gòu)的區(qū)別進行了詳細的分析介紹,需要的朋友參考下2013-05-05

