UI improvements, merge
This commit is contained in:
@@ -18,6 +18,61 @@ export async function loadPdfFromFile(file: File): Promise<PdfFile> {
|
||||
};
|
||||
}
|
||||
|
||||
export async function mergePdfFiles(
|
||||
basePdf: PdfFile,
|
||||
newPdf: PdfFile,
|
||||
insertAt: number
|
||||
): Promise<PdfFile> {
|
||||
const baseDoc = await PDFDocument.load(basePdf.arrayBuffer);
|
||||
const newDoc = await PDFDocument.load(newPdf.arrayBuffer);
|
||||
|
||||
const mergedDoc = await PDFDocument.create();
|
||||
|
||||
const basePageCount = baseDoc.getPageCount();
|
||||
const newPageCount = newDoc.getPageCount();
|
||||
|
||||
const clampedInsertAt = Math.min(Math.max(insertAt, 0), basePageCount);
|
||||
|
||||
const basePages = await mergedDoc.copyPages(
|
||||
baseDoc,
|
||||
Array.from({ length: basePageCount }, (_, i) => i)
|
||||
);
|
||||
const newPages = await mergedDoc.copyPages(
|
||||
newDoc,
|
||||
Array.from({ length: newPageCount }, (_, i) => i)
|
||||
);
|
||||
|
||||
// base pages before insertion
|
||||
for (let i = 0; i < clampedInsertAt; i += 1) {
|
||||
mergedDoc.addPage(basePages[i]);
|
||||
}
|
||||
|
||||
// inserted new pages
|
||||
for (let i = 0; i < newPages.length; i += 1) {
|
||||
mergedDoc.addPage(newPages[i]);
|
||||
}
|
||||
|
||||
// remaining base pages
|
||||
for (let i = clampedInsertAt; i < basePages.length; i += 1) {
|
||||
mergedDoc.addPage(basePages[i]);
|
||||
}
|
||||
|
||||
const bytes = await mergedDoc.save();
|
||||
const buffer = bytes.buffer.slice(
|
||||
bytes.byteOffset,
|
||||
bytes.byteOffset + bytes.byteLength
|
||||
);
|
||||
|
||||
const baseName = basePdf.name.replace(/\.pdf$/i, '');
|
||||
const newName = newPdf.name.replace(/\.pdf$/i, '');
|
||||
|
||||
return {
|
||||
name: `${baseName}_plus_${newName}.pdf`,
|
||||
arrayBuffer: buffer,
|
||||
pageCount: basePageCount + newPageCount,
|
||||
};
|
||||
}
|
||||
|
||||
export async function splitIntoSinglePages(
|
||||
pdf: PdfFile
|
||||
): Promise<SplitResult[]> {
|
||||
|
||||
Reference in New Issue
Block a user