如何使用pdf.js从pdf文档中获取元数据

8

你能否包含一段你使用的代码片段或其他内容? - amoebe
PDF文件中未填写作者字段。显示不同的文档,例如http://mozilla.github.io/pdf.js/web/viewer.html?file=/deuxdrop/pdf-docs/conversation-protocol.pdf。 - async5
4个回答

13

仅使用PDF.js库而不是第三方查看器,您可以使用promise获取元数据,方法如下:

Using just the PDF.js library without a thirdparty viewer, you can get metadata like so, utilizing promises.

PDFJS.getDocument(url).then(function (pdfDoc_) {
        pdfDoc = pdfDoc_;   
        pdfDoc.getMetadata().then(function(stuff) {
            console.log(stuff); // Metadata object here
        }).catch(function(err) {
           console.log('Error getting meta data');
           console.log(err);
        });

       // Render the first page or whatever here
       // More code . . . 
    }).catch(function(err) {
        console.log('Error getting PDF from ' + url);
        console.log(err);
    });

在将 pdfDoc 对象转储到控制台并查看其函数和属性后,我发现了这一点。我在原型中找到了该方法,并决定尝试一下。神奇的是,它起作用了!


我猜你的“利用承诺”这个短语是在拼写检查期间引入的错误? :) - unforgettableidSupportsMonica
要“查看”对象内容,您可以:console.log(JSON.stringify(stuff,null,2)) - user2677034
“PDFJS”是从哪里来的?当我尝试使用它时,一切都是未定义的。 - mondjunge
1
@mondjunge,我在5年前写了这个答案,不幸的是,我现在已经不再从事JavaScript工作了。该库可能已经更新。也许你可以在这里查看一些更新的示例代码?https://mozilla.github.io/pdf.js/examples/ - The Unknown Dev
我从pdf.js的github页面中引入了它,现在它可以工作了。猜测Firefox包含的pdf.js有某种保护层?! - mondjunge

2
您可以从PDFViewerApplication.documentInfo对象中获取文档的基本元数据信息。例如:要获取作者,请使用PDFViewerApplication.documentInfo.Author。

0

尝试:

await getDocument(url).promise.then(doc => doc.getMetadata())

0
pdfDoc.getMetadata(url).then(function(stuff) {
    var metadata = stuff.info.Title;
    if (metadata) {
        $('#element-html').text(stuff.info.Title); // Print metadata to html
    }
console.log(stuff); // Print metadata to console
}).catch(function(err) {
     console.log('Error getting meta data');
     console.log(err);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接