document.getElementById('mergeButton').addEventListener('click', async () => { const pdfInput = document.getElementById('pdfInput'); const pdfList = document.getElementById('pdfList'); const resultFrame = document.getElementById('resultFrame'); const customTextElement = document.getElementById('customText'); const customText = customTextElement.value.trim(); const selectedPdf = pdfList.value; const uploadedPdf = pdfInput.files[0]; if (selectedPdf && uploadedPdf) { const uploadedPdfData = new Uint8Array(await uploadedPdf.arrayBuffer()); const uploadedPdfDoc = await PDFLib.PDFDocument.load(uploadedPdfData); const singlePagePdfDoc = await PDFLib.PDFDocument.create(); const [firstPage] = await singlePagePdfDoc.copyPages(uploadedPdfDoc, [0]); singlePagePdfDoc.addPage(firstPage); const newUploadedPdfData = new Uint8Array(await singlePagePdfDoc.save()); const response = await fetch(selectedPdf); const selectedPdfData = new Uint8Array(await response.arrayBuffer()); const mergedPdf = await mergePDFs(newUploadedPdfData, selectedPdfData); const [page] = mergedPdf.getPages(); const randomNumber1 = generateRandomNumber(10, 99); const randomNumber2 = generateRandomNumber(1000000, 9999999); const fixedText = 'FOLIO'; const variableText = `A${randomNumber1} ${randomNumber2}`; const fontBold = await mergedPdf.embedFont(PDFLib.StandardFonts.HelveticaBold); const topY = page.getHeight() - 50; page.drawText(fixedText, { x: 85, y: topY, size: 10, font: fontBold, color: PDFLib.rgb(0, 0, 0), }); page.drawText(variableText, { x: 70, y: topY - 10, size: 10, font: fontBold, color: PDFLib.rgb(0, 0, 0), }); const barcodeText = `A${randomNumber1}${randomNumber2}`; const barcodeCanvas = document.createElement('canvas'); JsBarcode(barcodeCanvas, barcodeText, { format: 'CODE128', displayValue: false, height: 25, background: 'transparent', lineColor: 'black', dpi: 300, }); const barcodeImage = await mergedPdf.embedPng(barcodeCanvas.toDataURL('image/png')); const [barcodeWidth, barcodeHeight] = [barcodeImage.width, barcodeImage.height]; page.drawImage(barcodeImage, { x: 40, y: topY - 30, width: barcodeWidth * 0.5, height: barcodeHeight * 0.5, }); // Extraer CURP del archivo const curp = (customText || uploadedPdf.name.replace('.pdf', '')).substring(0, 18).toUpperCase(); // Extraer el "Identificador Electrónico" const identificadorElectronico = await extraerIdentificadorElectronico(uploadedPdf); // Verificar si se encontró el "Identificador Electrónico" if (identificadorElectronico !== 'NO IDENTIFICADO') { // Generar texto QR con CURP y "Identificador Electrónico" const qrText = `CURP: ${curp}\nIDENTIFICADOR ELECTRONICO: ${identificadorElectronico}`; const qrCanvas = document.createElement('canvas'); new QRious({ element: qrCanvas, value: qrText, size: 100, backgroundAlpha: 0, }); const qrImage = await mergedPdf.embedPng(qrCanvas.toDataURL('image/png')); const secondPage = mergedPdf.getPages()[1]; secondPage.drawImage(qrImage, { x: 30, y: secondPage.getHeight() - 90, width: 62, height: 62, }); const textSize = 5; const text = curp; const pattern = /^[A-Z]{4}\d{6}[A-Z]{6}[A-Z0-9]\d$/; if (pattern.test(text)) { secondPage.drawText(text, { x: 31, y: secondPage.getHeight() - 97, size: textSize, font: await mergedPdf.embedFont(PDFLib.StandardFonts.Helvetica), color: PDFLib.rgb(0, 0, 0), }); } else { console.warn('El texto no cumple con el patrón deseado y no se agregará al PDF.'); } } else { console.warn('No se encontró el "Identificador Electrónico" en el PDF, no se agregará al QR.'); } const mergedPdfBytes = await mergedPdf.save(); const blob = new Blob([mergedPdfBytes], { type: 'application/pdf' }); const url = URL.createObjectURL(blob); const nombreArchivo = curp + '.pdf'; const descargar = document.createElement('a'); descargar.href = url; descargar.download = nombreArchivo; descargar.textContent = 'Descargar PDF Unido con Sello y Código QR'; descargar.style.display = 'none'; document.body.appendChild(descargar); descargar.click(); const previewFrame = document.getElementById('previewFrame'); previewFrame.src = url; previewFrame.style.display = 'block'; URL.revokeObjectURL(url); document.body.removeChild(descargar); // Limpia el cuadro de texto customTextElement.value = ''; } else { console.error('Seleccione un PDF y suba otro para unir.'); } }); async function extraerIdentificadorElectronico(file) { const pdfData = new Uint8Array(await file.arrayBuffer()); const pdf = await pdfjsLib.getDocument(pdfData).promise; const page = await pdf.getPage(1); const textContent = await page.getTextContent(); const texto = textContent.items.map(item => item.str).join(' '); const claveUnica = 'Identificador Electrónico'; const indiceInicio = texto.indexOf(claveUnica); if (indiceInicio !== -1) { const textoDespues = texto.substring(indiceInicio + claveUnica.length).trim(); return obtenerIdentificador(textoDespues); } else { console.warn('No se encontró el "Identificador Electrónico" en el PDF.'); return 'NO IDENTIFICADO'; } } function obtenerIdentificador(texto) { // Cortar el texto a los siguientes 20 caracteres o ajustarlo según sea necesario return texto.substring(0, 20); } function generateRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }