首页 > 解决方案 > 如何使用 pdf.js 在注释中获取文本(使用过滤器 FlateDecode 编码的流)?

问题描述

需要用pdf.js解决:

a) 使用 pdf.js 可以使用 getAnnotations() 获取注释,但不能获取有关该注释中文本的任何信息。如何提取它?

b)如何从对象(参考:gen num)中获取流,例如:

/N: 8 0 R
/Filter:FlateDecode

标签: javascriptannotationspdfjs

解决方案


我使用以下方法回答了我的疑问:

我将解释问题和解决方案。

问题

使用 PDF.js 显示层从 PDF 中的注释中提取文本。

解决方案

PDF.js 有不同的层:

  1. 核心:解析二进制 PDF 的层
  2. 显示:使用核心层渲染 PDF 获取文档信息
  3. 查看器: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.jspdf.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)

    });

推荐阅读