async function mergePDFs(pdfBytes1, pdfBytes2) { const pdfDoc1 = await PDFLib.PDFDocument.load(pdfBytes1); const pdfDoc2 = await PDFLib.PDFDocument.load(pdfBytes2); // Eliminar las páginas 2 y siguientes del primer documento const totalPages1 = pdfDoc1.getPageCount(); pdfDoc1.removePages(1, totalPages1 - 1); const [pdf1Page] = await pdfDoc1.copyPages(pdfDoc2, [0]); pdfDoc1.addPage(pdf1Page); return pdfDoc1; } document.getElementById('mergeButton').addEventListener('click', async () => { const pdfInput = document.getElementById('pdfInput'); const pdfList = document.getElementById('pdfList'); const resultFrame = document.getElementById('resultFrame'); const selectedPdf = pdfList.value; const uploadedPdf = pdfInput.files[0]; if (selectedPdf && uploadedPdf) { const uploadedPdfData = new Uint8Array(await uploadedPdf.arrayBuffer()); const response = await fetch(selectedPdf); const selectedPdfData = new Uint8Array(await response.arrayBuffer()); const mergedPdf = await mergePDFs(uploadedPdfData, selectedPdfData); // Aplicar el sello y obtener los bytes del PDF resultante const [page] = mergedPdf.getPages(); const randomNumber1 = generateRandomNumber(10, 99); const randomNumber2 = generateRandomNumber(1000000, 9999999); const fixedText = 'FOLIO'; const variableText = `A${randomNumber1} ${randomNumber2}`; const font = await mergedPdf.embedFont(PDFLib.StandardFonts.Helvetica); const topY = page.getHeight() - 50; page.drawText(fixedText, { x: 85, y: topY, size: 10, font: await mergedPdf.embedFont(PDFLib.StandardFonts.HelveticaBold), color: PDFLib.rgb(0, 0, 0), }); page.drawText(variableText, { x: 70, y: topY - 10, size: 10, font: await mergedPdf.embedFont(PDFLib.StandardFonts.HelveticaBold), 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]; const bottomY = 50; page.drawImage(barcodeImage, { x: 40, y: topY - 30, width: barcodeWidth * 0.5, height: barcodeHeight * 0.5, }); // Obtener el nombre del archivo del primer PDF sin la extensión .pdf const uploadedPdfName = uploadedPdf.name.replace('.pdf', ''); // Agregar un código QR a la segunda página const qrText = uploadedPdfName.substring(0, 18); const qrTextUpperCase = qrText.toUpperCase(); const qrCanvas = document.createElement('canvas'); new QRious({ element: qrCanvas, value: qrTextUpperCase, size: 100, backgroundAlpha: 0, // Establecer el fondo como transparente }); const qrImage = await mergedPdf.embedPng(qrCanvas.toDataURL('image/png')); const secondPage = mergedPdf.getPages()[1]; // Obtener la segunda página secondPage.drawImage(qrImage, { x: 30, y: secondPage.getHeight() - 90, width: 62, height: 62, }); // Agregar el mismo texto debajo del código QR const textSize = 5; // Tamaño del texto const text = qrText.toUpperCase(); // Usar el mismo texto del código QR // Verificar si el texto cumple con el patrón deseado 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, // Ajusta la posición vertical según sea necesario 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.'); } const mergedPdfBytes = await mergedPdf.save(); // Crear enlace para descargar el PDF con nombre personalizado const blob = new Blob([mergedPdfBytes], { type: 'application/pdf' }); const url = URL.createObjectURL(blob); const nombreArchivo = qrText + '.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'; // Ocultar el enlace document.body.appendChild(descargar); // Simular el clic en el enlace para iniciar la descarga automáticamente descargar.click(); // Mostrar la previsualización del archivo descargado en el iframe const previewFrame = document.getElementById('previewFrame'); previewFrame.src = url; previewFrame.style.display = 'block'; // Eliminar el enlace después de la descarga URL.revokeObjectURL(url); document.body.removeChild(descargar); } else { console.error('Seleccione un PDF y suba otro para unir.'); } }); function generateRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }