Added Pdf File wrapper. migrated merge to use it

This commit is contained in:
Saud Fatayerji 2023-11-11 23:43:39 +03:00
parent 1b0a881ad6
commit 3fad22c4fe
2 changed files with 64 additions and 4 deletions

View File

@ -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<Uint8Array> {
export async function mergePDFs(files: PdfFile[]): Promise<PdfFile> {
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);
};

View File

@ -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<void> {
if (this.pdfLib) {
this.byteArray = await this.pdfLib.save();
this.pdfLib = null;
}
}
async convertToLibPdf(): Promise<void> {
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<void> {
const pdfPromises = files.map(s => s.convertToByteArray());
await Promise.all(pdfPromises);
}
export async function convertAllToLibPdf(files: PdfFile[]): Promise<void> {
const pdfPromises = files.map(s => s.convertToLibPdf());
await Promise.all(pdfPromises);
}