extract, rotate, split
This commit is contained in:
25
public/functions/extractPages.js
Normal file
25
public/functions/extractPages.js
Normal file
@@ -0,0 +1,25 @@
|
||||
const { PDFDocument, ParseSpeeds } = PDFLib;
|
||||
|
||||
export const extractPages = async (snapshot, pagesToExtractArray) => {
|
||||
const pdfDoc = await PDFDocument.load(snapshot)
|
||||
|
||||
// TODO: invent a better format for pagesToExtractArray and convert it.
|
||||
return createSubDocument(pdfDoc, pagesToExtractArray);
|
||||
};
|
||||
|
||||
export async function createSubDocument(pdfDoc, pagesToExtractArray) {
|
||||
const subDocument = await PDFDocument.create();
|
||||
|
||||
// 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();
|
||||
}
|
||||
18
public/functions/rotatePDF.js
Normal file
18
public/functions/rotatePDF.js
Normal file
@@ -0,0 +1,18 @@
|
||||
const { PDFDocument, ParseSpeeds, degrees } = PDFLib;
|
||||
|
||||
export const rotatePages = async (snapshot, rotation) => {
|
||||
// Load the original PDF file
|
||||
const pdfDoc = await PDFDocument.load(snapshot, {
|
||||
parseSpeed: ParseSpeeds.Fastest,
|
||||
});
|
||||
|
||||
const pages = pdfDoc.getPages();
|
||||
|
||||
pages.forEach(page => {
|
||||
// Change page size
|
||||
page.setRotation(degrees(rotation))
|
||||
});
|
||||
|
||||
// Serialize the modified document
|
||||
return pdfDoc.save();
|
||||
};
|
||||
26
public/functions/splitPDF.js
Normal file
26
public/functions/splitPDF.js
Normal file
@@ -0,0 +1,26 @@
|
||||
import { createSubDocument } from "./extractPages.js";
|
||||
|
||||
const { PDFDocument, ParseSpeeds } = PDFLib;
|
||||
|
||||
export const splitPDF = async (snapshot, splitAfterPageArray) => {
|
||||
const pdfDoc = await PDFDocument.load(snapshot)
|
||||
|
||||
const numberOfPages = pdfDoc.getPages().length;
|
||||
|
||||
let pagesArray = [];
|
||||
let splitAfter = splitAfterPageArray.shift();
|
||||
const subDocuments = [];
|
||||
|
||||
for (let i = 0; i < numberOfPages; i++) {
|
||||
if(i > splitAfter && pagesArray.length > 0) {
|
||||
subDocuments.push(await createSubDocument(pdfDoc, pagesArray));
|
||||
splitAfter = splitAfterPageArray.shift();
|
||||
pagesArray = [];
|
||||
}
|
||||
pagesArray.push(i);
|
||||
}
|
||||
subDocuments.push(await createSubDocument(pdfDoc, pagesArray));
|
||||
pagesArray = [];
|
||||
|
||||
return subDocuments;
|
||||
};
|
||||
Reference in New Issue
Block a user