Other improvements in the splitPDF() function

This commit is contained in:
2026-07-28 12:52:00 +02:00
parent df6110fc59
commit 5213c58819
2 changed files with 15 additions and 18 deletions
+15 -18
View File
@@ -227,6 +227,12 @@ async function splitExcelFile(inputFile) {
}
}
const getCodiceFiscale = (pageText) => {
if (!pageText) return null;
const match = pageText.match(/Codice fiscale:\s*([A-Za-z0-9]+)/i);
return match ? match[1].toUpperCase() : null; // match[1] is the captured code
};
async function splitPDF(numRows, inputFile, tempFiles) {
console.log(`Loading pdf file: ${ inputFile }...\n`);
let parser;
@@ -242,27 +248,18 @@ async function splitPDF(numRows, inputFile, tempFiles) {
// 2. we use pdf-lib to create and edit a pdf file
const srcPdf = await PDFDocument.load(existingPdfBytes);
// if there are duplicates (back to back duplicates), I only have to print one copy
// if there are duplicates, I only have to print one copy
if (pagesNumber > numRows) { // comparison between the number of pages of the pdf file and those of the excel file
let displayNumPage = 1;
let lastPrintedText = null;
let index = 1;
for (let i = 0; i < pagesNumber; i++) {
let pageText = result.pages[i].text.trim();
// Only print if the current page is different from the immediate previous page
if (pageText !== lastPrintedText) {
/*console.log(`--- PAGE ${displayNumPage} ---`);
console.log(pageText);
console.log("\n");*/
// Remember this text for the next iteration
lastPrintedText = pageText;
await processPage(srcPdf, i, tempFiles);
displayNumPage++;
// we use optional chaining ?. so that when we encounter null or undefined values, the code doesn't crash
const prevCF = getCodiceFiscale(result.pages[i + 1]?.text);
const currentCF = getCodiceFiscale(result.pages[i].text);
if (prevCF && prevCF === currentCF) {
continue;
}
i++;
await processPage(srcPdf, i, tempFiles);
index++;
}
}
else {