.net 用C#阅读PDF文本图像

olmpazwi  于 2023-11-20  发布在  .NET
关注(0)|答案(3)|浏览(242)

我需要阅读PDF文件,并需要转换为HTML。目前我使用iTextsharp阅读PDF。是否有任何带有适当文档的dll来阅读PDF文件
谢谢

lymnna71

lymnna711#

ITextSharp是相当体面和相当容易实现..这里是一个小的例子,阅读的pdf和把文本到一个字符串,然后打印出来的标签上的webforms页面:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using iTextSharp.text.pdf;
  8. using iTextSharp.text.pdf.parser;
  9. namespace pdfreadertest
  10. {
  11. public partial class _Default : System.Web.UI.Page
  12. {
  13. protected void Page_Load(object sender, EventArgs e)
  14. {
  15. GetTextFromPDFFile(@"c:\example.pdf", 1);
  16. }
  17. public void GetTextFromPDFFile(string pdfFile, int pageNumber)
  18. {
  19. // Call the reader to read the pdf file
  20. PdfReader pdfReader = new PdfReader(pdfFile);
  21. // Extract the text from the pdf reader and put into a string
  22. string pdfText = PdfTextExtractor.GetTextFromPage(pdfReader, pageNumber);
  23. // Try and close the reader
  24. try
  25. {
  26. pdfReader.Close();
  27. }
  28. catch{ }
  29. // Put the string (pdf text) into a label to display on page
  30. this.lblPdfText.Text = pdfText;
  31. }
  32. }
  33. }

字符串
希望能帮上忙。

展开查看全部
2ul0zpep

2ul0zpep2#

如果你在2023年遇到这个问题,你可以用C#(NET Core)阅读PDF中的文本。这可以通过itext7 nuget包实现。(包含此代码的工作解决方案的链接可以在here中找到)。

  1. using iText.Kernel.Pdf;
  2. using iText.Kernel.Pdf.Canvas.Parser;
  3. using iText.Kernel.Pdf.Canvas.Parser.Listener;
  4. namespace ScanTextInPDFs
  5. {
  6. internal class Program
  7. {
  8. public static async Task Main(string[] args)
  9. {
  10. string executingDirectory = AppContext.BaseDirectory;
  11. byte[] bytes = await File.ReadAllBytesAsync($"{executingDirectory}PDFs\\Brochure.pdf");
  12. string textToFind = "Lorem ipsum";
  13. bool foundText = false;
  14. using (MemoryStream memoryStream = new MemoryStream(bytes))
  15. {
  16. using PdfReader pdfReader = new PdfReader(memoryStream);
  17. using PdfDocument pdfDocument = new PdfDocument(pdfReader);
  18. for (int page = 1; page <= pdfDocument.GetNumberOfPages(); page++)
  19. {
  20. PdfPage pdfPage = pdfDocument.GetPage(page);
  21. string pageText = PdfTextExtractor.GetTextFromPage(pdfPage, new SimpleTextExtractionStrategy());
  22. if (pageText.Contains(textToFind, StringComparison.Ordinal))
  23. foundText = true;
  24. }
  25. }
  26. if (foundText)
  27. Console.WriteLine($"Found '{textToFind}' in the pdf.");
  28. else
  29. Console.WriteLine($"Did not find '{textToFind}' in the pdf.");
  30. }
  31. }
  32. }

字符串

展开查看全部
k4emjkb1

k4emjkb13#

我认为iTextSharp是最受欢迎的一个,即使有几个其他的库,如iText.Net,PDF夏普,夏普PDF等谷歌它,你会发现他们很多。我用过iTextSharp,我喜欢它。

相关问题