如何使用pdf.js获取pdf标题

How to get pdf title using pdf.js?

本文关键字:pdf 标题 获取 js 何使用      更新时间:2023-09-26

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

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 对象中,但这里似乎并非如此,我在文档中找不到任何关于此的内容。我在这里错过了什么或做错了什么吗?

我把它修:)代码现在如下所示:

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();
      });
  });
});

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