n8n-nodes-pdf-page-split
Version:
n8n node to split PDF documents into individual pages
174 lines • 8.31 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfPageSplit = void 0;
const n8n_workflow_1 = require("n8n-workflow");
const pdf_lib_1 = require("pdf-lib");
class PdfPageSplit {
constructor() {
this.description = {
displayName: 'PDF Page Split',
name: 'pdfPageSplit',
icon: 'file:pdfPageSplit.svg',
group: ['transform'],
version: 1,
description: 'Split PDF into individual pages',
defaults: {
name: 'PDF Page Split',
},
inputs: ['main'],
outputs: ['main'],
properties: [
{
displayName: 'Binary Property',
name: 'binaryPropertyName',
type: 'string',
default: 'data',
required: true,
description: 'Name of the binary property containing the PDF file.',
},
{
displayName: 'Output Options',
name: 'outputOptions',
type: 'collection',
placeholder: 'Add Option',
default: {},
options: [
{
displayName: 'File Name Prefix',
name: 'fileNamePrefix',
type: 'string',
default: 'page_',
description: 'Prefix for the output file names.',
},
{
displayName: 'Include Page Number',
name: 'includePageNumber',
type: 'boolean',
default: true,
description: 'Whether to include page number in the output file names.',
},
{
displayName: 'Start Number At',
name: 'startNumberAt',
type: 'number',
default: 1,
description: 'The number to start counting pages from.',
typeOptions: {
minValue: 0,
},
},
{
displayName: 'Page Range',
name: 'pageRange',
type: 'string',
default: '',
placeholder: '1-5,8,11-13',
description: 'Range of pages to split (e.g., "1-5,8,11-13"). Leave empty to split all pages.',
},
],
},
],
};
}
async execute() {
var _a;
const items = this.getInputData();
const returnData = [];
for (let i = 0; i < items.length; i++) {
try {
const binaryPropertyName = this.getNodeParameter('binaryPropertyName', i);
const outputOptions = this.getNodeParameter('outputOptions', i, {});
if (!((_a = items[i].binary) === null || _a === void 0 ? void 0 : _a[binaryPropertyName])) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'No binary data found', { itemIndex: i });
}
const fileBufferEncoded = items[i].binary[binaryPropertyName].data;
const fileBuffer = Buffer.from(fileBufferEncoded, 'base64');
const pdfBytes = Uint8Array.from(fileBuffer);
const pdfDoc = await pdf_lib_1.PDFDocument.load(pdfBytes);
const pageCount = pdfDoc.getPageCount();
if (pageCount === 0) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'The PDF document has no pages', { itemIndex: i });
}
let pagesToProcess = [];
const pageRange = outputOptions.pageRange || '';
if (pageRange) {
const ranges = pageRange.split(',').map(r => r.trim());
for (const range of ranges) {
if (range.includes('-')) {
const [start, end] = range.split('-').map(Number);
for (let page = start; page <= end; page++) {
if (page > 0 && page <= pageCount) {
pagesToProcess.push(page - 1);
}
}
}
else {
const page = Number(range);
if (page > 0 && page <= pageCount) {
pagesToProcess.push(page - 1);
}
}
}
}
else {
pagesToProcess = Array.from({ length: pageCount }, (_, i) => i);
}
const originalFilename = items[i].binary[binaryPropertyName].fileName || 'document.pdf';
const fileNamePrefix = outputOptions.fileNamePrefix || 'page_';
const includePageNumber = outputOptions.includePageNumber !== false;
const startNumberAt = outputOptions.startNumberAt || 1;
for (let pageIndex of pagesToProcess) {
try {
let newItem = {
json: {
...items[i].json,
pageNumber: pageIndex + 1,
totalPages: pageCount,
},
binary: {},
};
let pageNumber = '';
if (includePageNumber) {
const displayPageNum = pageIndex + startNumberAt;
pageNumber = String(displayPageNum).padStart(String(pageCount + startNumberAt - 1).length, '0');
}
const fileNameBase = originalFilename.replace(/\.[^/.]+$/, '');
let fileName = `${fileNamePrefix}${pageNumber ? pageNumber + '_' : ''}${fileNameBase}`;
const newPdfDoc = await pdf_lib_1.PDFDocument.create();
const [copiedPage] = await newPdfDoc.copyPages(pdfDoc, [pageIndex]);
newPdfDoc.addPage(copiedPage);
const newPdfBytes = await newPdfDoc.save();
newItem.binary[binaryPropertyName] = await this.helpers.prepareBinaryData(Buffer.from(newPdfBytes), `${fileName}.pdf`, 'application/pdf');
returnData.push(newItem);
}
catch (error) {
console.error(`Error processing page ${pageIndex + 1}: ${(error === null || error === void 0 ? void 0 : error.message) || 'Unknown error'}`);
returnData.push({
json: {
error: `Error processing page ${pageIndex + 1}: ${(error === null || error === void 0 ? void 0 : error.message) || 'Unknown error'}`,
pageNumber: pageIndex + 1,
totalPages: pageCount,
},
pairedItem: { item: i },
});
}
}
}
catch (error) {
if (this.continueOnFail()) {
returnData.push({
json: {
error: (error === null || error === void 0 ? void 0 : error.message) || 'Unknown error',
},
pairedItem: { item: i },
});
continue;
}
throw error;
}
}
return [returnData];
}
}
exports.PdfPageSplit = PdfPageSplit;
//# sourceMappingURL=PdfPageSplit.node.js.map