
我们需要以编程方式注释一个.pdf文件,然后从该注释中提取文本。用例是说突出显示黄色的几个单词,然后不仅获得有关注释的元数据(这已经解决了),而且还突出显示了该注释中的文本。
创建注释并获取有关它的元信息的要求不是问题。使用pdf.js一个可以使用getAnnotations()返回一个承诺的函数,该承诺填充了有关 .pdf 中所有注释的信息。
//The data doesn't contain the text information within the annotations using this method in pdf.js
var annotateMeta = page.getAnnotations().then(function (data) {
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
问题是对象数据具有颜色和坐标信息,但没有关于该注释中文本的任何信息。
有谁知道我们如何使用这些库中的任何一个(或实际上任何其他 .js 库)来获取 .pdf 文件中注释中的文本值?
我们需要将现有的多个 PDF 导入到一个新的 PDF 中。部分代码与iText in Action 第二版6.2.1 节中的示例代码类似:
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(
document, new FileOutputStream(RESULT));
document.open();
PdfPTable table = new PdfPTable(2);
PdfReader reader = new PdfReader(MovieTemplates.RESULT);
int n = reader.getNumberOfPages();
PdfImportedPage page;
for (int i = 1; i <= n; i++) {
page = writer.getImportedPage(reader, i);
table.addCell(Image.getInstance(page));
}
document.add(table);
document.close();
Run Code Online (Sandbox Code Playgroud)
然而,我们刚刚意识到,在处理带有注释的可填充 PDF 时(在我们的例子中,这些 PDF 已经填充了数据),所有填充的数据都会在新 PDF 中丢失。
我们在书中的同一部分找到了答案:
了解呈现页面内容所需的资源与页面的交互功能之间的区别非常重要。一般来说,这些功能称为注释。它们包括链接、文本注释和表单字段。注释不是内容流的一部分。它们没有列在页面的资源字典中,而是列在注释字典中。使用 时不会复制这些交互功能
PdfImportedPage,这意味着使用该类的getImportedPage()方法复制页面时,所有交互性都会丢失PdfWriter。
但是保留这些注释的解决方案是什么?
可以添加 GestureRecognizer 或设置触摸 PDFAnnotation
func setDocumentAnnotation() {
let anotation:PDFAnnotation = PDFAnnotation(bounds: CGRect(x: pointX, y: pointY, width: pointW, height: pointH), forType: .highlight, withProperties: nil)
anotation.color = .yellow
anotation.endLineStyle = .circle
guard let page = pdfView.currentPage else {return}
page.addAnnotation(anotation)
}
@objc func annotationTapping(_ sender: UITapGestureRecognizer){
print("------- annotationTapping ------")
}
Run Code Online (Sandbox Code Playgroud)