Files
documenso/packages/lib/server-only/pdf/normalize-pdf.ts
T
Lucas Smith a1d4bec143 fix: accept owner-password protected pdfs (#3396)
Strip encryption from PDFs that open with an empty user password via
libpdf's ignorePermissions, still rejecting user-password PDFs.

Upgrade @libpdf/core to 0.5.1, which also keeps overlapping and layered
text intact during text extraction.

Resolves #3303
2026-09-26 11:23:33 +10:00

39 lines
994 B
TypeScript

import { PDF } from '@libpdf/core';
import { AppError } from '../../errors/app-error';
export const normalizePdf = async (pdf: Buffer, options: { flattenForm?: boolean } = {}) => {
const shouldFlattenForm = options.flattenForm ?? true;
const pdfDoc = await PDF.load(pdf).catch((e) => {
console.error(`PDF normalization error: ${e.message}`);
throw new AppError('INVALID_DOCUMENT_FILE', {
message: 'The document is not a valid PDF or is password protected',
});
});
if (pdfDoc.isEncrypted) {
if (!pdfDoc.isAuthenticated) {
throw new AppError('INVALID_DOCUMENT_FILE', {
message: 'The document is password protected',
});
}
pdfDoc.removeProtection({ ignorePermissions: true });
}
pdfDoc.flattenLayers();
const form = pdfDoc.getForm();
if (shouldFlattenForm && form) {
form.flatten();
pdfDoc.flattenAnnotations();
}
const normalizedPdfBytes = await pdfDoc.save();
return Buffer.from(normalizedPdfBytes);
};