Stirling-PDF/shared-operations/src/functions/splitPDF.ts

34 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-10-26 20:53:02 +02:00
import { selectPages } from "./subDocumentFunctions";
import { PdfFile } from '../wrappers/PdfFile';
export type SplitPdfParamsType = {
file: PdfFile;
splitAfterPageArray: number[];
}
export async function splitPDF(params: SplitPdfParamsType): Promise<PdfFile[]> {
const { file, splitAfterPageArray } = params;
const byteFile = await file.convertToPdfLibFile();
if (!byteFile?.pdfLib) return [];
2023-10-17 03:40:54 +02:00
const numberOfPages = byteFile.pdfLib.getPages().length;
2023-10-17 03:40:54 +02:00
let pagesArray: number[] = [];
2023-10-17 03:40:54 +02:00
let splitAfter = splitAfterPageArray.shift();
const subDocuments: PdfFile[] = [];
2023-10-17 03:40:54 +02:00
for (let i = 0; i < numberOfPages; i++) {
if(splitAfter && i > splitAfter && pagesArray.length > 0) {
subDocuments.push(await selectPages({file:byteFile, pagesToExtractArray:pagesArray}));
2023-10-17 03:40:54 +02:00
splitAfter = splitAfterPageArray.shift();
pagesArray = [];
}
pagesArray.push(i);
2023-10-17 03:40:54 +02:00
}
subDocuments.push(await selectPages({file:byteFile, pagesToExtractArray:pagesArray}));
2023-10-17 03:40:54 +02:00
pagesArray = [];
return subDocuments;
};