【问题标题】:How to get pdf title using pdf.js? [duplicate]如何使用 pdf.js 获取 pdf 标题? [复制]
【发布时间】:2015-09-05 20:49:37
【问题描述】:

问题是:如何使用 pdf.js 获取 pdf 文件的名称?我正在从 node 运行一个 pdf.js 示例的变体,我想知道是否有可能得到它。我一直在搜索 pdf.js 的 docs/source,但找不到任何明显的东西。我正在使用这段代码,它(到目前为止)显示了在给定文件夹中找到的每个文件的页数(在这种情况下,是运行此代码的目录):

var fs = require('fs');
var glob = require('glob');

global.window = global;
global.navigator = { userAgent: "node" };
global.PDFJS = {};
global.DOMParser = require('./domparsermock.js').DOMParserMock;

require('../../build/singlefile/build/pdf.combined.js');
glob("**/*.pdf", function (er, files) {
for(var i = 0; i < files.length; i++){
var data = new Uint8Array(fs.readFileSync(files[i]));
PDFJS.getDocument(data).then(function (doc) {
      var numPages = doc.numPages;
      console.log('Number of Pages: ' + numPages);
      console.log();
    }).then(function () {
      console.log('# End of Document');
    }, function (err) {
      console.error('Error: ' + err);
    });
   }
});

我认为文件名作为属性或类似属性存在于 doc 对象中,但这里似乎并非如此,我在文档中找不到任何关于此的内容。我在这里有什么遗漏或做错了吗?

【问题讨论】:

  • 你可以用普通的node js东西来抓取文件名。文件来自哪里是请求还是您在目录中搜索它等等。?
  • @user2879041 - 请查看我编辑的问题
  • 文件名在files[i],不确定你在问什么...
  • @JuanMendes 但是当我尝试在第一个 then() 调用的函数中使用它们时(我得到页数),它们看起来是未定义的。即使我拥有它们,我也无法将每个文件名与其相应的页数相关联。不是现在的代码。
  • ...好吧,我找到了一些东西:如果我尝试执行console.log('Number of Pages: ' + numPages + ', filename: ' + files[i]);,它会输出“页数:2,文件名:未定义”,因为在匿名函数内部,我用作index 总是 2,所以这似乎是一个范围或 js 闭包问题。

标签: javascript pdfjs


【解决方案1】:

我修好了 :) 代码现在看起来像这样:

var fs = require('fs');
var glob = require('glob');

global.window = global;
global.navigator = { userAgent: "node" };
global.PDFJS = {};
global.DOMParser = require('./domparsermock.js').DOMParserMock;

require('../../build/singlefile/build/pdf.combined.js');
glob("**/*.pdf", function (er, files) {

//this is the essential change: use a forEach() instead of the for loop
files.forEach(function(file){
    var data = new Uint8Array(fs.readFileSync(file));
    PDFJS.getDocument(data)
      .then(function (doc) {
        var numPages = doc.numPages;
        console.log('File name: ' + file + ', Number of Pages: ' + numPages);
        console.log();
      });
  });
});

希望它对某人有所帮助,并感谢您的快速回复:)

【讨论】:

  • 它不起作用的原因是循环内的files[i]是因为then()内的代码是异步运行的。因此,在它们运行时,i 等于 files.length 并且 files[i] 未定义。也就是说,i 变量被所有then 回调共享。通过使用forEach,您将为每个文件创建一个单独的闭包!很好地解决了你自己。见stackoverflow.com/questions/18560708/…
  • 离题:你可以使用 asynchronous fs.readFile 并“承诺”你的整个管道:从读取文件的承诺开始,.then 做一个@ 987654333@解析PDF文档,.then处理文档。现在,同步文件读取和异步处理有点奇怪。
猜你喜欢
  • 1970-01-01
  • 2015-05-05
  • 2014-05-09
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 2020-12-04
  • 1970-01-01
  • 2017-03-30
相关资源
最近更新 更多