Stirling-PDF/shared-operations/functions/extractPages.js

26 lines
935 B
JavaScript
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';
2023-10-26 20:53:02 +02:00
export async function extractPages(snapshot, pagesToExtractArray) {
2023-10-26 22:41:48 +02:00
const pdfDoc = await PDFDocument.load(snapshot)
2023-10-17 03:40:54 +02:00
// TODO: invent a better format for pagesToExtractArray and convert it.
2023-10-26 20:53:02 +02:00
return createSubDocument(pdfDoc, pagesToExtractArray);
2023-10-17 03:40:54 +02:00
};
2023-10-26 20:53:02 +02:00
export async function createSubDocument(pdfDoc, pagesToExtractArray) {
2023-10-26 22:41:48 +02:00
const subDocument = await PDFDocument.create();
2023-10-17 03:40:54 +02:00
// Check that array max number is not larger pdf pages number
if(Math.max(...pagesToExtractArray) >= pdfDoc.getPageCount()) {
throw new Error(`The PDF document only has ${pdfDoc.getPageCount()} pages and you tried to extract page ${Math.max(...pagesToExtractArray)}`);
}
const copiedPages = await subDocument.copyPages(pdfDoc, pagesToExtractArray);
for (let i = 0; i < copiedPages.length; i++) {
subDocument.addPage(copiedPages[i]);
}
return subDocument.save();
}