afpp
Version:
Async Fast PDF Parser for Node.js — dependency-light, TypeScript-first, production-ready.
53 lines • 1.96 kB
JavaScript
import { getDocument, PDFDateString } from 'pdfjs-dist/legacy/build/pdf.mjs';
import { resolveInput } from './resolveInput.js';
const toOptionalString = (value) => {
if (typeof value === 'string' && value.length > 0)
return value;
return undefined;
};
const toOptionalDate = (value) => {
if (!value)
return undefined;
const date = PDFDateString.toDateObject(value);
return date ?? undefined;
};
export async function getPdfMetadata(input, options) {
const documentInitParameters = await resolveInput(input);
let isEncrypted = false;
const loadingTask = getDocument(documentInitParameters);
// PasswordResponses.NEED_PASSWORD = 1, INCORRECT_PASSWORD = 2
loadingTask.onPassword = (updateCallback, reason) => {
isEncrypted = true;
if (reason === 1 && options?.password) {
updateCallback(options.password);
}
else {
const msg = reason === 2 ? 'Incorrect Password' : 'No password given';
const err = new Error(msg);
err.name = 'PasswordException';
throw err;
}
};
const pdfDocument = await loadingTask.promise;
try {
const { numPages } = pdfDocument;
const { info } = await pdfDocument.getMetadata();
const record = info;
return {
title: toOptionalString(record['Title']),
author: toOptionalString(record['Author']),
subject: toOptionalString(record['Subject']),
creator: toOptionalString(record['Creator']),
producer: toOptionalString(record['Producer']),
creationDate: toOptionalDate(record['CreationDate']),
modificationDate: toOptionalDate(record['ModDate']),
pageCount: numPages,
isEncrypted,
};
}
finally {
await pdfDocument.cleanup();
await loadingTask.destroy();
}
}
//# sourceMappingURL=getPdfMetadata.js.map