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

26 lines
953 B
TypeScript
Raw Normal View History

2023-10-26 20:53:02 +02:00
2023-11-12 14:57:53 +01:00
import { degrees } from 'pdf-lib';
import { PdfFile, fromPdfLib } from '../wrappers/PdfFile';
2023-11-12 14:57:53 +01:00
export async function rotatePages(file: PdfFile, rotation: number|number[]): Promise<PdfFile> {
const pdfDoc = await file.getAsPdfLib();
const pages = pdfDoc.getPages();
2023-11-12 14:57:53 +01:00
if (Array.isArray(rotation)) {
if (rotation.length != pages.length) {
throw new Error(`Number of given rotations '${rotation.length}' is not the same as the number of pages '${pages.length}'`)
}
for (let i=0; i<rotation.length; i++) {
const oldRotation = pages[i].getRotation().angle
pages[i].setRotation(degrees(oldRotation + rotation[i]))
}
} else {
pages.forEach(page => {
// Change page size
const oldRotation = page.getRotation().angle
page.setRotation(degrees(oldRotation + rotation))
});
}
2023-11-12 14:57:53 +01:00
return fromPdfLib(pdfDoc, file.filename);
};