使用PDFSharp在PDF中查找单词
本文关键字:查找 单词 PDF PDFSharp 使用 | 更新日期: 2023-09-27 18:12:04
我用的是PDFSharp。我需要帮助。我需要检查一下文件中是否有abc这个词。例子:
11abcee = true
444abcggw = true
778ab = false
我写了这段代码,但它没有像预期的那样工作:
PdfDocument document = PdfReader.Open("c:''abc.pdf");
PdfDictionary dictionary = new PdfDictionary(document);
string a = dictionary.Elements.GetString("MTZ");
if (a.Equals("MTZ"))
{
MessageBox.Show("OK", "");
}
else
{
MessageBox.Show("NO", "");
}
我错过了什么吗?
老问题,但这里有一个例子。
注意:c# 7.0+需要使用新的局部变量赋值。
注意:这个例子使用从包管理器安装的PDFSharp。Install-Package PdfSharp -Version 1.50.5147"
注:对于我的要求,我只需要搜索我的pdf文件的第一页,更新它需要的。
using (PdfDocument inputDocument = PdfReader.Open(filePath, PdfDocumentOpenMode.Import))
{
if (searchPDFPage(ContentReader.ReadContent(inputDocument.Pages[0]), searchText))
{
// match found.
}
}
此代码查找以磅号开头的cString, OP需要使用Contains字符串函数。
private bool searchPDFPage(CObject cObject, string searchText)
{
if (cObject is COperator cOperator)
{
if (cOperator.OpCode.Name == OpCodeName.Tj.ToString() ||
cOperator.OpCode.Name == OpCodeName.TJ.ToString())
{
foreach (var cOperand in cOperator.Operands)
{
if (searchPDFPage(cOperand, searchText))
{
return true;
}
}
}
}
else if (cObject is CSequence cSequence)
{
foreach (var element in cSequence)
{
if (searchPDFPage(element, searchText))
{
return true;
}
}
}
else if (cObject is CString cString)
{
if (cString.Value.StartsWith("#"))
{
if (cString.Value.Substring(2) == searchText)
{
return true;
}
}
}
return false;
}
Credit:这个例子是根据这个答案修改的:使用PdfSharp从PDF中提取文本
也许这个SO条目会对您有所帮助:PDFSharp alter Text repositioning。链接到这里-使用PDFSharp的文本提取示例。