如何在 C# 中以编程方式搜索 PDF 文档 [已关闭]

问题描述 投票:0回答:3

我需要搜索 pdf 文件以查看是否存在某个字符串。有问题的字符串肯定被编码为文本(即它不是图像或任何东西)。我尝试过像纯文本一样搜索文件,但这不起作用。

可以这样做吗?有没有 .net2.0 的库可以为我提取/解码 pdf 文件中的所有文本?

c# .net search pdf
3个回答
16
投票

有一些可用的库。 查看 http://www.codeproject.com/KB/cs/PDFToText.aspxhttp://itextsharp.sourceforge.net/

这需要一点努力,但这是可能的。


3
投票

您可以使用 Docotic.Pdf 库 搜索 PDF 文件中的文本。

这是示例代码:

static void searchForText(string path, string text)
{
    using (PdfDocument pdf = new PdfDocument(path))
    {
        for (int i = 0; i < pdf.Pages.Count; i++)
        {
            string pageText = pdf.Pages[i].GetText();
            int index = pageText.IndexOf(text, 0, StringComparison.CurrentCultureIgnoreCase);
            if (index != -1)
                Console.WriteLine("'{0}' found on page {1}", text, i);
        }
    }
}

该库还可以从整个文档或任何文档页面中提取格式化文本和纯文本。

免责声明:我为 Bit Miracle 工作,该库的供应商。


1
投票
在绝大多数情况下,不可能通过在记事本中打开 PDF 来直接搜索 PDF 的内容 - 即使在少数情况下(取决于 PDF 的构建方式),您也只能由于 PDF 内部处理文本的方式,能够搜索单个单词。

我的公司有一个商业解决方案,可以让您从 PDF 文件中提取文本。我在下面为您提供了一些示例代码,

如本页所示,演示了如何从 PDF 文件中的文本中搜索特定字符串。

using System; using System.IO; using QuickPDFDLL0718; namespace QPLConsoleApp { public class QPL { public static void Main() { // This example uses the DLL edition of Quick PDF Library // Create an instance of the class and give it the path to the DLL PDFLibrary QP = new PDFLibrary("QuickPDFDLL0718.dll"); // Check if the DLL was loaded successfully if (QP.LibraryLoaded()) { // Insert license key here / Check the license key if (QP.UnlockKey("...") == 1) { QP.LoadFromFile(@"C:\Program Files\Quick PDF Library\DLL\GettingStarted.pdf"); int iPageCount = QP.PageCount(); int PageNumber = 1; int MatchesFound = 0; while (PageNumber <= iPageCount) { QP.SelectPage(PageNumber); string PageText = QP.GetPageText(3); using (StreamWriter TempFile = new StreamWriter(QP.GetTempPath() + "temp" + PageNumber + ".txt")) { TempFile.Write(PageText); } string[] lines = File.ReadAllLines(QP.GetTempPath() + "temp" + PageNumber + ".txt"); string[][] grid = new string[lines.Length][]; for (int i = 0; i < lines.Length; i++) { grid[i] = lines[i].Split(','); } foreach (string[] line in grid) { string FindMatch = line[11]; // Update this string to the word that you're searching for. // It can be one or more words (i.e. "sunday" or "last sunday". if (FindMatch.Contains("characters")) { Console.WriteLine("Success! Word match found on page: " + PageNumber); MatchesFound++; } } PageNumber++; } if (MatchesFound == 0) { Console.WriteLine("Sorry! No matches found."); } else { Console.WriteLine(); Console.WriteLine("Total: " + MatchesFound + " matches found!"); } Console.ReadLine(); } } } } }
    
© www.soinside.com 2019 - 2024. All rights reserved.