我需要搜索pdf文件以查看某個字符串是否存在。有問題的字符串肯定是編碼爲文本(即它不是圖像或任何東西)。我試圖只是搜索文件,就好像它是純文本,但這不起作用。如何以編程方式在c中搜索PDF文檔#
可以做到這一點嗎? .net2.0是否有任何圖書館爲我提取/解碼PDF文件中的所有文本?
我需要搜索pdf文件以查看某個字符串是否存在。有問題的字符串肯定是編碼爲文本(即它不是圖像或任何東西)。我試圖只是搜索文件,就好像它是純文本,但這不起作用。如何以編程方式在c中搜索PDF文檔#
可以做到這一點嗎? .net2.0是否有任何圖書館爲我提取/解碼PDF文件中的所有文本?
這裏有幾個圖書館。 結賬http://www.codeproject.com/KB/cs/PDFToText.aspx 和http://itextsharp.sourceforge.net/
它需要一點努力,但它是可能的。
絕大多數情況下,無法直接通過在記事本中打開來搜索PDF內容 - 甚至在少數情況下(取決於PDF的構建方式),您都可以由於PDF在內部處理文本的方式,因此只能搜索單個單詞。
我的公司有一個商業解決方案,可以讓你從PDF文件中提取文本。我在下面包含了一些示例代碼,as shown on this page,演示瞭如何從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();
}
}
}
}
}
您可以使用Docotic.Pdf library來搜索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);
}
}
}
圖書館還可以extract formatted and plain text從整個文檔或文檔頁面。
聲明:我爲圖書館供應商Bit Miracle工作。
+1 for iTextSharp。它應該能夠做到你所需要的。 – jeremcc 2009-02-20 03:10:58