From 5213c588191209c02b2ce151f621c62f1816db35 Mon Sep 17 00:00:00 2001 From: "Denise D." Date: Tue, 28 Jul 2026 12:52:00 +0200 Subject: [PATCH] Other improvements in the splitPDF() function --- file.js | 33 +++++++++++++++------------------ temp.js | 0 2 files changed, 15 insertions(+), 18 deletions(-) create mode 100644 temp.js diff --git a/file.js b/file.js index e37fbd7..073b1e6 100644 --- a/file.js +++ b/file.js @@ -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 { diff --git a/temp.js b/temp.js new file mode 100644 index 0000000..e69de29