mirror of
https://github.com/documenso/documenso
synced 2026-04-21 13:27:18 +00:00
32 lines
939 B
TypeScript
32 lines
939 B
TypeScript
import { PDFDocument } from '@cantoo/pdf-lib';
|
|
|
|
import { AppError } from '../../errors/app-error';
|
|
import { flattenAnnotations } from './flatten-annotations';
|
|
import { flattenForm, removeOptionalContentGroups } from './flatten-form';
|
|
|
|
export const normalizePdf = async (pdf: Buffer, options: { flattenForm?: boolean } = {}) => {
|
|
const shouldFlattenForm = options.flattenForm ?? true;
|
|
|
|
const pdfDoc = await PDFDocument.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',
|
|
});
|
|
}
|
|
|
|
removeOptionalContentGroups(pdfDoc);
|
|
|
|
if (shouldFlattenForm) {
|
|
await flattenForm(pdfDoc);
|
|
flattenAnnotations(pdfDoc);
|
|
}
|
|
|
|
return Buffer.from(await pdfDoc.save());
|
|
};
|