diff --git a/shared-operations/functions/mergePDFs.ts b/shared-operations/functions/mergePDFs.ts index ef4a30a4..433a2a2e 100644 --- a/shared-operations/functions/mergePDFs.ts +++ b/shared-operations/functions/mergePDFs.ts @@ -1,16 +1,20 @@ import { PDFDocument } from 'pdf-lib'; +import { PdfFile, convertAllToLibPdf, fromPDFDocument } from '../wrappers/PdfFile'; -export async function mergePDFs(snapshots: (string | Uint8Array | ArrayBuffer)[]): Promise { +export async function mergePDFs(files: PdfFile[]): Promise { + + await convertAllToLibPdf(files); const mergedPdf = await PDFDocument.create(); - for (let i = 0; i < snapshots.length; i++) { - const pdfToMerge = await PDFDocument.load(snapshots[i]); + for (let i = 0; i < files.length; i++) { + const pdfToMerge = files[i].pdfLib; + if (!pdfToMerge) continue; const copiedPages = await mergedPdf.copyPages(pdfToMerge, pdfToMerge.getPageIndices()); copiedPages.forEach((page) => mergedPdf.addPage(page)); } - return mergedPdf.save(); + return fromPDFDocument(mergedPdf); }; \ No newline at end of file diff --git a/shared-operations/wrappers/PdfFile.ts b/shared-operations/wrappers/PdfFile.ts new file mode 100644 index 00000000..386170b9 --- /dev/null +++ b/shared-operations/wrappers/PdfFile.ts @@ -0,0 +1,56 @@ + +import { PDFDocument } from 'pdf-lib'; + +export class PdfFile { + byteArray: Uint8Array | null; + pdfLib: PDFDocument | null; + filename?: string; + + constructor() { + this.byteArray = null; + this.pdfLib = null; + } + + async convertToByteArray(): Promise { + if (this.pdfLib) { + this.byteArray = await this.pdfLib.save(); + this.pdfLib = null; + } + } + async convertToLibPdf(): Promise { + if (this.byteArray) { + this.pdfLib = await PDFDocument.load(this.byteArray, { + updateMetadata: false, + }); + this.byteArray = null; + } + } +} + +export function fromMulterFile(value: Express.Multer.File, filename?: string) { + return fromUint8Array(value.buffer, filename) +} +export function fromUint8Array(value: Uint8Array, filename?: string) { + const out = new PdfFile(); + out.byteArray = value; + out.filename = filename; + return out; +} +export function fromPDFDocument(value: PDFDocument, filename?: string) { + const out = new PdfFile(); + out.pdfLib = value; + out.filename = filename; + return out; +} + +export async function convertAllToByteArray(files: PdfFile[]): Promise { + const pdfPromises = files.map(s => s.convertToByteArray()); + await Promise.all(pdfPromises); + +} + +export async function convertAllToLibPdf(files: PdfFile[]): Promise { + const pdfPromises = files.map(s => s.convertToLibPdf()); + await Promise.all(pdfPromises); + +}