documenso/packages/lib/server-only/pdf/normalize-pdf.ts
Lucas Smith 9035240b4d
refactor: replace pdf-sign with libpdf/core for PDF operations (#2403)
Migrate from @documenso/pdf-sign and @cantoo/pdf-lib to @libpdf/core
for all PDF manipulation and signing operations. This includes:

- New signing transports for Google Cloud KMS and local certificates
- Consolidated PDF operations using libpdf API
- Added TSA (timestamp authority) helper for digital signatures
- Removed deprecated flatten and insert utilities
- Updated tests to use new PDF library
2026-01-21 15:16:23 +11:00

32 lines
804 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',
});
});
if (pdfDoc.isEncrypted) {
throw new AppError('INVALID_DOCUMENT_FILE', {
message: 'The document is encrypted',
});
}
pdfDoc.flattenLayers();
const form = pdfDoc.getForm();
if (shouldFlattenForm && form) {
form.flatten();
pdfDoc.flattenAnnotations();
}
return Buffer.from(await pdfDoc.save());
};