如何在 NodeJS 中读取 PDF 创建和修改日期
问题:
你有一个 PDF 文件,你想知道其创建和修改日期:不是文件本身存储的日期,而是 PDF 元数据中的日期。
解决方案
此解决方案假设你使用支持 async/await 的 NodeJS 8+ 版本。
你可以使用 pdfjs 读取这些日期。首先使用以下命令安装
install_pdfjs3.sh
npm install pdfjs-dist然后使用此代码提取日期。
read_pdf_dates.js
const pdfjs = require('pdfjs-dist');
async function readPDFDates() {
const pdf = await pdfjs.getDocument('mypdf.pdf');
const metadata = await pdf.getMetadata();
const modDate = new Date(metadata.metadata._metadata['xmp:modifydate']);
const createDate = new Date(metadata.metadata._metadata['xmp:createdate']);
return [modDate, createDate]
}
readPDFDates().then(([modDate, createDate]) => {
console.log(`Creation date: ${createDate}`)
console.log(`Modification date: ${modDate}`)
}).catch(err => {
console.error(`Error while reading PDF: ${err}`)
})我见过的 PDF 文件使用 ISO8601 风格格式,但没有时区规范。因此代码假设时间是本地时区。
注意:元数据例如是以下对象(并非所有 PDF 都有所有属性):
pdf_metadata_example.txt
{ info:
{ PDFFormatVersion: '1.5',
IsAcroFormPresent: false,
IsXFAPresent: false,
Title: 'Microsoft Word - mypdf',
Author: 'uli',
Creator: 'PScript5.dll Version 5.2.2',
Producer: 'Acrobat Distiller 9.3.0 (Windows)',
CreationDate: 'D:20100209100924+01\'00\'',
ModDate: 'D:20100209100924+01\'00\'' },
metadata:
Metadata {
_metadata:
{ 'dc:format': 'application/pdf',
'dc:creator': 'peter',
'dc:title': 'Microsoft Word - mypdf',
'xmp:createdate': '2010-02-09T10:09:24+01:00',
'xmp:creatortool': 'PScript5.dll Version 5.2.2',
'xmp:modifydate': '2010-02-09T10:09:24+01:00',
'pdf:producer': 'Acrobat Distiller 9.3.0 (Windows)',
'xmpmm:documentid': 'uuid:2fd66f45-5f2a-4dd6-8cb0-297ce85ee9e1',
'xmpmm:instanceid': 'uuid:f6e62218-4b40-47c7-837b-6cb1e6e90995' } },Check out similar posts by category:
Javascript, PDF
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow