43 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-10-26 21:53:02 +03:00
2023-11-12 16:57:53 +03:00
import { PDFPage } from 'pdf-lib';
import { PdfFile, fromPdfLib } from '../wrappers/PdfFile';
2023-10-16 23:11:33 +02:00
export type ScaleContentParamsType = {
file: PdfFile;
scaleFactor: number|number[];
}
export async function scaleContent(params: ScaleContentParamsType): Promise<PdfFile> {
const { file, scaleFactor } = params;
2023-11-12 16:57:53 +03:00
const pdfDoc = await file.getAsPdfLib();
2023-10-16 23:11:33 +02:00
const pages = pdfDoc.getPages();
2023-11-12 16:57:53 +03:00
if (Array.isArray(scaleFactor)) {
if (scaleFactor.length != pages.length) {
throw new Error(`Number of given scale factors '${scaleFactor.length}' is not the same as the number of pages '${pages.length}'`)
}
for (let i=0; i<scaleFactor.length; i++) {
scalePage(pages[i], scaleFactor[i]);
}
} else {
pages.forEach(page => scalePage(page, scaleFactor));
}
return fromPdfLib(pdfDoc, file.filename);
};
2023-10-16 23:11:33 +02:00
2023-11-12 16:57:53 +03:00
function scalePage(page: PDFPage, scaleFactor: number) {
const width = page.getWidth();
const height = page.getHeight();
2023-10-16 23:11:33 +02:00
2023-11-12 16:57:53 +03:00
// Scale content
page.scaleContent(scaleFactor, scaleFactor);
const scaled_diff = {
width: Math.round(width - scaleFactor * width),
height: Math.round(height - scaleFactor * height),
};
2023-10-16 23:11:33 +02:00
2023-11-12 16:57:53 +03:00
// Center content in new page format
page.translateContent(Math.round(scaled_diff.width / 2), Math.round(scaled_diff.height / 2));
}