Stirling-PDF/shared-operations/functions/mergePDFs.ts

20 lines
619 B
TypeScript
Raw Normal View History

2023-10-26 20:53:02 +02:00
2023-10-26 22:41:48 +02:00
import { PDFDocument } from 'pdf-lib';
import { PdfFile, convertAllToLibPdf, fromPDFDocument } from '../wrappers/PdfFile';
2023-10-26 20:53:02 +02:00
export async function mergePDFs(files: PdfFile[]): Promise<PdfFile> {
await convertAllToLibPdf(files);
2023-10-26 22:41:48 +02:00
const mergedPdf = await PDFDocument.create();
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 fromPDFDocument(mergedPdf);
};