如果您只是添加文本和/或图像,那么您应该能够检查正常的文本流。我认为您执行的搜索返回了注释结果,因为您谈论的是一种注释类型的“邮票”,但您没有使用它们。您正在使用 aPdfStamper
来修改现有文档。
下面是一个完整的示例,展示了如何创建基本 PDF,然后通过添加具有唯一字符串的表来修改它,然后最终在 PDF 中搜索唯一字符串。代码中的注释应该能解释一切,希望如此。请注意底部的警告。
/* Setup */
//Test files
var file1 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file1.pdf");
var file2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file2.pdf");
//Stamp Text
var stampText = "**UNIQUE_STAMP_TEXT**";
/* Step 1 */
//Create a basic simple file, nothing special here
using (var fs = new FileStream(file1, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
doc.Add(new Paragraph("Hello World"));
doc.Close();
}
}
}
/* Step 2 */
//Create our second file based on the first file
using (var reader = new PdfReader(file1)) {
using (var fs = new FileStream(file2, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var stamper = new PdfStamper(reader, fs)) {
//Get the raw content stream "above" the existing content
var canvas = stamper.GetOverContent(1);
//Create a basic single column table
var table = new PdfPTable(1);
table.SetTotalWidth(new float[] { 500 });
var cellFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.RED);
//Add our special stamp text
table.AddCell(new PdfPCell(new Phrase(stampText, cellFont)));
//Draw the table onto the canvas
table.WriteSelectedRows(0, 1, 50, 50, canvas);
}
}
}
/* Step 3 */
//Search the previously created PDF for the given string
bool hasStampText = false;
using (var reader = new PdfReader(file2)) {
var text = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1);
//WARNING: PdfPTable will wrap text if needed. Unless you can gaurantee that your text fits into the provided cell
// you might want to have some additional logic to search for your unique string.
hasStampText = text.Contains(stampText);
}