javascript - 如何使用 pdf.js 在注释中获取文本(使用过滤器 FlateDecode 编码的流)?
问题描述
需要用pdf.js解决:
a) 使用 pdf.js 可以使用 getAnnotations() 获取注释,但不能获取有关该注释中文本的任何信息。如何提取它?
b)如何从对象(参考:gen num)中获取流,例如:
/N: 8 0 R
/Filter:FlateDecode
解决方案
我使用以下方法回答了我的疑问:
- 来自brendandahl(GitHub)的pdf.js.utils (浏览器)
- PDF 参考和 PDF 规范的 Adobe 扩展
我将解释问题和解决方案。
问题
使用 PDF.js 显示层从 PDF 中的注释中提取文本。
解决方案
PDF.js 有不同的层:
- 核心:解析二进制 PDF 的层
- 显示:使用核心层渲染 PDF 获取文档信息
- 查看器:Firefox 和其他浏览器扩展中 PDF 查看器的 UI
为了从注释中提取文本,必须在核心层和显示层中工作。
一、核心层:
使用注释中的所有文本创建一个公共属性(annotationText)
a) 修改 src/core/annotation.js
a.1)类注解构造函数:添加一行并结束构造函数
// Expose public properties using a data object.
this.data = {
...
annotationText: this._extractText(params) // -> Add this line *****
};
}
a.2)类注释- 添加提取文本的方法:
_extractText(params) {
// AP - Appearance Dictionary
let appearanceDictionary = params.dict.get('AP');
// No AP
if (typeof appearanceDictionary === 'undefined') {
return '';
}
// N - Stream
let normalAppearance = appearanceDictionary.xref.fetch(appearanceDictionary._map.N);
normalAppearance.getBytes()
// No text
if (typeof normalAppearance.buffer === 'undefined') {
return '';
}
let numParentheses = 0;
let streamText = '';
for (let i = 0; i < normalAppearance.buffer.length; i++) {
if (String.fromCharCode(normalAppearance.buffer[i]) === ")") {
numParentheses--;
}
if (numParentheses > 0) {
streamText += String.fromCharCode(normalAppearance.buffer[i]);
}
if (String.fromCharCode(normalAppearance.buffer[i]) === "(") {
numParentheses++;
}
}
return streamText;
}
b) 将所有src/文件打包成两个生产脚本(pdf.js和pdf.worker.js)
$ gulp generic
二、显示层:
在annotationText中显示文本
page.getAnnotations().then(
function (annotations) {
let textInAnnotations = ""
for (annotation in annotations) {
textInAnnotations = textInAnnotations + " - " + annotations[annotation].annotationText
}
console.log("Text in annotations: "+textInAnnotations)
});
推荐阅读
- javascript - 声明中不可访问的解构对象
- python - Boto3 wait_until_exists 可用图像不等待
- android - 使用 Android 工具链构建时,CMake 找不到库和包
- python - 将字典中的每个数值加一的函数
- php - 在 Laravel 中使用带有 json_decode 对象的集合
- c++ - 如何从带有 ROS 的 yaml 文件中读取包含元组的数组?
- r - 使用 eventReactive 找不到对象错误
- python - 使用 subprocess.Popen 运行被中断
- python - 在 Python 中记录可重复的操作
- java - 如何在地图上编写聚合函数
根据键值计算 MIN、MAX 和 AVG