2023-10-26 21:53:02 +03:00
|
|
|
|
2024-01-04 20:17:54 -05:00
|
|
|
import { degrees } from "pdf-lib";
|
|
|
|
|
import { PdfFile, RepresentationType } from "../wrappers/PdfFile";
|
2023-10-22 00:55:28 +02:00
|
|
|
|
2024-01-04 20:17:54 -05:00
|
|
|
export interface RotateParamsType {
|
2023-11-14 03:26:42 +03:00
|
|
|
file: PdfFile;
|
|
|
|
|
rotation: number|number[];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function rotatePages(params: RotateParamsType): Promise<PdfFile> {
|
|
|
|
|
const { file, rotation } = params;
|
|
|
|
|
|
2023-11-16 02:24:10 +03:00
|
|
|
const pdfDoc = await file.pdfLibDocument;
|
|
|
|
|
const pages = pdfDoc.getPages();
|
2023-10-22 00:55:28 +02:00
|
|
|
|
2023-11-12 16:57:53 +03:00
|
|
|
if (Array.isArray(rotation)) {
|
|
|
|
|
if (rotation.length != pages.length) {
|
2024-01-04 20:17:54 -05:00
|
|
|
throw new Error(`Number of given rotations '${rotation.length}' is not the same as the number of pages '${pages.length}'`);
|
2023-11-12 16:57:53 +03:00
|
|
|
}
|
|
|
|
|
for (let i=0; i<rotation.length; i++) {
|
2024-01-04 20:17:54 -05:00
|
|
|
const oldRotation = pages[i].getRotation().angle;
|
|
|
|
|
pages[i].setRotation(degrees(oldRotation + rotation[i]));
|
2023-11-12 16:57:53 +03:00
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
pages.forEach(page => {
|
|
|
|
|
// Change page size
|
2024-01-04 20:17:54 -05:00
|
|
|
const oldRotation = page.getRotation().angle;
|
|
|
|
|
page.setRotation(degrees(oldRotation + rotation));
|
2023-11-12 16:57:53 +03:00
|
|
|
});
|
|
|
|
|
}
|
2023-10-22 00:55:28 +02:00
|
|
|
|
2023-11-16 02:24:10 +03:00
|
|
|
return new PdfFile(file.originalFilename, pdfDoc, RepresentationType.PDFLibDocument, file.filename+"_rotated");
|
2024-01-04 20:17:54 -05:00
|
|
|
}
|