根据以下帖子:
iTextSharp PDF Reading highlighed text (highlight annotations) using C#
这段代码:
for (int i = pageFrom; i <= pageTo; i++) {
PdfDictionary page = reader.GetPageN(i);
PdfArray annots = page.GetAsArray(iTextSharp.text.pdf.PdfName.ANNOTS);
if (annots!=null)
foreach (PdfObject annot in annots.ArrayList) {
PdfDictionary annotation = (PdfDictionary)PdfReader.GetPdfObject(annot);
PdfString contents = annotation.GetAsString(PdfName.CONTENTS);
// now use the String value of contents
}
}
}
正在努力提取 PDF 注释。但是为什么以下相同的代码对高亮不起作用(特别是 PdfName.HIGHLIGHT 不起作用):
for (int i = pageFrom; i <= pageTo; i++) {
PdfDictionary page = reader.GetPageN(i);
PdfArray annots = page.GetAsArray(iTextSharp.text.pdf.PdfName.HIGHLIGHT);
if (annots!=null)
foreach (PdfObject annot in annots.ArrayList) {
PdfDictionary annotation = (PdfDictionary)PdfReader.GetPdfObject(annot);
PdfString contents = annotation.GetAsString(PdfName.CONTENTS);
// now use the String value of contents
}
}
}
最佳答案
请查看 ISO-32000-1(又名 PDF 引用)中的表 30。它的标题是“页面对象中的条目”。在这些条目中,您可以找到一个名为 Annots
的键。 .它的值(value)是:
(Optional) An array of annotation dictionaries that shall contain indirect references to all annotations associated with the page (see 12.5, "Annotations").
您将找不到带有诸如
Highlight
之类的键的条目。 ,因此当您有以下行时,返回的数组为空是正常的:PdfArray annots = page.GetAsArray(iTextSharp.text.pdf.PdfName.HIGHLIGHT);
您需要按照您已经完成的方式获取注释:
PdfArray annots = page.GetAsArray(iTextSharp.text.pdf.PdfName.ANNOTS);
现在你需要遍历这个数组并寻找带有
Subtype
的注释。等于 Highlight
.这种类型的注释列在 ISO-32000-1 的表 169 中,标题为“注释类型”。换句话说,您假设页面字典包含键为
Highlight
的条目。错了,如果您阅读整个规范,您还会发现您所做的另一个错误假设。您错误地假设突出显示的文本存储在 Contents
中。注释的输入。这表明对注释与页面内容的性质缺乏了解。您要查找的文本存储在页面的内容流中。页面的内容流独立于页面的注释。因此,要获取突出显示的文本,您需要获取存储在
Highlight
中的坐标。注释(存储在 QuadPoints
数组中),您需要使用这些坐标来解析页面内容中这些坐标处的文本。
关于.net - 如何使用 iTextSharp 从 PDF 中提取突出显示的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26652411/