mindee
Version:
Mindee Client Library for Node.js
81 lines (80 loc) • 3.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPages = extractPages;
exports.countPages = countPages;
const handler_1 = require("../errors/handler");
const pdf_lib_1 = require("@cantoo/pdf-lib");
const input_1 = require("../input");
const errors_1 = require("../errors");
const logger_1 = require("../logger");
/**
* Cut pages from a pdf file. If pages index are out of bound, it will throw an error.
* @param file
* @param pageOptions
* @returns the new cut pdf file.
*/
async function extractPages(file, pageOptions) {
const currentPdf = await pdf_lib_1.PDFDocument.load(file, {
ignoreEncryption: true,
password: ""
});
const newPdf = await pdf_lib_1.PDFDocument.create();
const pageCount = currentPdf.getPageCount();
if (pageCount < pageOptions.onMinPages) {
logger_1.logger.debug(`File skipped because it had less than ${pageOptions} pages (${pageCount}).`);
return { file: file, totalPagesRemoved: 0 };
}
if (pageOptions.pageIndexes.length > pageCount) {
handler_1.errorHandler.throw(new errors_1.MindeeError("The total indexes of pages to cut is superior to the total page count of the file (" +
pageCount +
")."));
}
const pageIndexes = [];
pageOptions.pageIndexes.forEach((pageIndex) => {
if (pageIndex < 0) {
pageIndexes.push(pageCount - Math.abs(pageIndex));
}
else {
pageIndexes.push(pageIndex);
}
});
if (!pageIndexes.every((v) => currentPdf.getPageIndices().includes(v))) {
handler_1.errorHandler.throw(new errors_1.MindeeError(`Some indexes pages
(${pageIndexes.join(",")})
don't exist in the file
(${currentPdf.getPageIndices().join(", ")})`));
}
if (pageOptions.operation === input_1.PageOptionsOperation.KeepOnly) {
const keptPages = await newPdf.copyPages(currentPdf, pageIndexes);
keptPages.forEach((keptPage) => {
newPdf.addPage(keptPage);
});
}
else if (pageOptions.operation === input_1.PageOptionsOperation.Remove) {
const pagesToKeep = currentPdf
.getPageIndices()
.filter((v) => !pageIndexes.includes(v));
const keptPages = await newPdf.copyPages(currentPdf, pagesToKeep);
keptPages.forEach((keptPage) => {
newPdf.addPage(keptPage);
});
}
else {
throw new Error(`The operation ${pageOptions.operation} is not available.`);
}
const sumRemovedPages = pageCount - newPdf.getPageCount();
const fileBuffer = Buffer.from(await newPdf.save());
return { file: fileBuffer, totalPagesRemoved: sumRemovedPages };
}
/**
* Count the number of pages in a pdf file.
* @param file
* @returns the number of pages in the file.
*/
async function countPages(file) {
const currentPdf = await pdf_lib_1.PDFDocument.load(file, {
ignoreEncryption: true,
password: ""
});
return currentPdf.getPageCount();
}