【问题标题】:Reading pdf from url with node.js using PDF.js使用 PDF.js 从带有 node.js 的 url 读取 pdf
【发布时间】:2021-01-19 04:22:19
【问题描述】:

我正在尝试从 pdf 的 url 中提取 pdf 的文本。按照 pdf.js 网站上的示例,我了解如何在客户端呈现 pdf,但是当我在服务器端执行此操作时遇到了问题。

我使用npm i pdfjs-dist下载了包

我尝试使用下面的代码作为加载 pdf 的简单示例:

var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/examples/learning/helloworld.pdf';
var pdfjsLib = require("pdfjs-dist")
var loadingTask = pdfjsLib.getDocument(url);

loadingTask.promise.then(function (pdf) {
    console.log(pdf);
}).catch(function (error){
    console.log(error)
})

但是当我运行它时,我得到以下错误:

  message: 'The browser/environment lacks native support for critical functionality used by the PDF.js library (e.g. `ReadableStream` and/or `Promise.allSettled`); please use an ES5-compatible build instead.',
  name: 'UnknownErrorException',
  details: 'Error: The browser/environment lacks native support for critical functionality used by the PDF.js library (e.g. `ReadableStream` and/or `Promise.allSettled`); please use an ES5-compatible build instead.'

关于如何进行此操作的任何想法?我要做的就是从它的 URL 中提取 pdf 的文本。我正在尝试使用 nodejs 来做这个服务器端。感谢您的意见!

【问题讨论】:

    标签: javascript node.js pdf.js


    【解决方案1】:

    您需要导入 pdf.js 的 es5 构建。下面的代码应该可以工作:

    var pdfjsLib = require("pdfjs-dist/es5/build/pdf.js");
    var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/examples/learning/helloworld.pdf';
    var loadingTask = pdfjsLib.getDocument(url);
    
    loadingTask.promise.then(function (pdf) {
        console.log(pdf);
    }).catch(function (error){
        console.log(error)
    })
    
    

    还可以查看 https://github.com/mozilla/pdf.js/blob/master/examples/node/getinfo.js 以获取使用 node.js 的工作示例

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题(浏览器/环境缺乏对 PDF.js(例如 ReadableStream 和/或Promise.allSettled);请改用ES5-compatible build) 但是使用 Angular 8 所以我在这里留下解决方案以防有人需要它:

      packaje.json配置:

      • Angular 版本:8.2.14
      • pdfjs-dist:2.4.456

      组件:

      import * as pdfjs from 'pdfjs-dist/es5/build/pdf';
      import { pdfjsworker } from 'pdfjs-dist/es5/build/pdf.worker.entry';
      
      pdfjs.GlobalWorkerOptions.workerSrc = pdfjsworker;
      

      【讨论】:

      • 甜蜜的解决方案。我在 react (17.0) 应用程序中遇到了同样的问题,我使用的是 react-pdf 模块,但后来删除了安装了上述版本的模块并且它工作正常。谢谢
      【解决方案3】:

      在 node js 项目中使用最新版本的 pdfjs-dist (2.8.335) 时,我也遇到了同样的问题,正如其他答案中提到的,我们需要更改路径来解决这个问题。

      但在我的情况下,路径 - pdfjs-dist/es5/build/pdf 不起作用。

      在最新版本中改为pdfjs-dist/legacy/build/pdf.js

      【讨论】:

        猜你喜欢
        • 2021-07-15
        • 2011-09-11
        • 1970-01-01
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        • 2016-09-19
        • 2020-06-05
        • 2019-10-24
        相关资源
        最近更新 更多