UNPKG

afpp

Version:

Async Fast PDF Parser for Node.js — dependency-light, TypeScript-first, production-ready.

77 lines 2.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getPdfMetadata = getPdfMetadata; const promises_1 = require("node:fs/promises"); const pdf_mjs_1 = require("pdfjs-dist/legacy/build/pdf.mjs"); const toOptionalString = (value) => { if (typeof value === 'string' && value.length > 0) return value; return undefined; }; const toOptionalDate = (value) => { if (!value) return undefined; const date = pdf_mjs_1.PDFDateString.toDateObject(value); return date ?? undefined; }; async function getPdfMetadata(input, options) { const documentInitParameters = {}; switch (true) { case typeof input === 'string': documentInitParameters.data = new Uint8Array(await (0, promises_1.readFile)(input)); break; case Buffer.isBuffer(input): documentInitParameters.data = new Uint8Array(input); break; case input instanceof Uint8Array: documentInitParameters.data = input; break; case input instanceof URL: documentInitParameters.url = input; break; default: throw new Error(`Invalid source type: ${typeof input}`); } documentInitParameters.verbosity = pdf_mjs_1.VerbosityLevel.ERRORS; documentInitParameters.disableAutoFetch = true; documentInitParameters.disableStream = true; documentInitParameters.disableRange = true; let isEncrypted = false; const loadingTask = (0, pdf_mjs_1.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 { pdfDocument.cleanup(); await pdfDocument.destroy(); loadingTask.destroy(); } } //# sourceMappingURL=getPdfMetadata.js.map