@neilkrichi/pdf-cli
Version:
A CLI tool for splitting and merging PDF files
47 lines (46 loc) • 2.21 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergePDFs = mergePDFs;
const pdf_lib_1 = require("pdf-lib");
const promises_1 = require("fs/promises");
const chalk_1 = __importDefault(require("chalk"));
const path_1 = __importDefault(require("path"));
const utils_1 = require("./utils");
async function mergePDFs(files, output = "merged.pdf") {
try {
console.log(chalk_1.default.blue("🔄 Merging PDFs..."));
// Check if output file exists
const normalizedOutput = path_1.default.normalize(output);
const shouldContinue = await (0, utils_1.confirmOverwrite)(normalizedOutput);
if (!shouldContinue) {
console.log(chalk_1.default.yellow("⚠️ Operation cancelled"));
process.exit(0);
}
const mergedPdf = await pdf_lib_1.PDFDocument.create();
for (const file of files) {
// Normalize the path to handle spaces and special characters
const normalizedPath = path_1.default.normalize(file);
console.log(chalk_1.default.yellow(`📄 Adding ${normalizedPath}...`));
try {
const pdfBytes = await (0, promises_1.readFile)(normalizedPath);
const pdf = await pdf_lib_1.PDFDocument.load(pdfBytes);
const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
copiedPages.forEach((page) => mergedPdf.addPage(page));
}
catch (fileError) {
console.error(chalk_1.default.red(`❌ Error processing ${normalizedPath}: `), fileError);
throw new Error(`Failed to process ${normalizedPath}`);
}
}
const mergedPdfBytes = await mergedPdf.save();
await (0, promises_1.writeFile)(normalizedOutput, mergedPdfBytes);
console.log(chalk_1.default.green(`✅ Merged PDF saved as: ${normalizedOutput}`));
}
catch (error) {
console.error(chalk_1.default.red("❌ Error merging PDFs: "), error);
process.exit(1);
}
}