根据您的library reference link,您使用Debenu PDFLibrary 函数ReplaceTag。根据this Debenu knowledge base article
ReplaceTag 函数只是替换页面内容流中的文本,因此对于大多数文档来说它不会有任何效果。对于一些简单的文档,它可能能够替换内容,但这实际上取决于 PDF 的构建方式。本质上和做的一样:
DPL.CombineContentStreams();
string content = DPL.GetContentStreamToString();
DPL.SetPageContentFromString(content.Replace("Moby", "Mary"));
这对于任何通用 PDF 库都应该是可能的,绝对是 iText(Sharp):
void VerySimpleReplaceText(string OrigFile, string ResultFile, string origText, string replaceText)
{
using (PdfReader reader = new PdfReader(OrigFile))
{
byte[] contentBytes = reader.GetPageContent(1);
string contentString = PdfEncodings.ConvertToString(contentBytes, PdfObject.TEXT_PDFDOCENCODING);
contentString = contentString.Replace(origText, replaceText);
reader.SetPageContent(1, PdfEncodings.ConvertToBytes(contentString, PdfObject.TEXT_PDFDOCENCODING));
new PdfStamper(reader, new FileStream(ResultFile, FileMode.Create, FileAccess.Write)).Close();
}
}
警告:就像在 Debenu 函数的情况下一样,对于大多数文档,此代码不会产生任何影响,甚至会具有破坏性。对于一些简单的文档,它可能能够替换内容,但这实际上取决于 PDF 的构建方式。
顺便说一句,Debenu knowledge base article 继续:
如果您使用 Debenu Quick PDF Library 和标准字体创建了 PDF,则 ReplaceTag 功能应该可以工作 - 但是,对于使用执行子集字体甚至字距调整(单词将被拆分)的工具创建的 PDF,然后搜索文本可能不会以简单的格式出现在内容中。
因此,简而言之,ReplaceTag 功能仅适用于某些有限的场景,并不是您可以依赖的用于搜索和替换文本的功能。
因此,如果在您迁移到托管解决方案期间您还更改了源文档的创建方式,那么 Debenu PDFLibrary 函数ReplaceTag 和上面的代码都可能无法更改内容随心所欲。