mirror of
https://github.com/documenso/documenso
synced 2026-04-21 13:27:18 +00:00
This PR introduces automatic detection and placement of fields and
recipients based on PDF placeholders.
The placeholders have the following structure:
- `{{fieldType,recipientPosition,fieldMeta}}`
- `{{text,r1,required=true,textAlign=right,fontSize=50}}`
When the user uploads a PDF document containing such placeholders, they
get converted automatically to Documenso fields and assigned to
recipients.
34 lines
854 B
TypeScript
34 lines
854 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();
|
|
}
|
|
|
|
const normalizedPdfBytes = await pdfDoc.save();
|
|
|
|
return Buffer.from(normalizedPdfBytes);
|
|
};
|