循环批量填充PDF表单时仅最后一个文件正常生成的问题咨询及替代方案寻求
循环批量填充PDF表单时仅最后一个文件正常生成的问题咨询及替代方案寻求
各位好,我遇到了一个批量填充PDF表单的问题,想请教下大家:
我需要实现一个功能,接收多组数据并分别填充到PDF表单中,生成多个独立的PDF文件。目前单个文件的填充逻辑已经跑通了,但当我用循环批量处理时,只有最后一个生成的文件是正确填充内容的,前面的文件虽然会被创建,但打开后都是空的。
我的脚本嵌入在简单HTML页面里,点击按钮触发功能,代码如下:
<!DOCTYPE html> <html> <head> <title>Fill PDF with JavaScript</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf-lib/1.16.0/pdf-lib.js"></script> </head> <body> <button id="fillPDF">Rellenar PDF</button> <script> // function to fill the fields of a PDF async function fillPDF(namePDF, dataPDF) { const existingPdfBytes = await fetch('https://api.codetabs.com/v1/proxy/?quest=https://pdf-lib.js.org/assets/dod_character.pdf').then((res) => res.arrayBuffer()); // Create a PDF from existing bytes const pdfDoc = await PDFLib.PDFDocument.load(existingPdfBytes); const form = pdfDoc.getForm(); // Fill the fields form.getTextField('CharacterName 2').setText(dataPDF.name); form.getTextField('Age').setText(dataPDF.number); form.getTextField('Allies').setText(dataPDF.phoneNum); form.flatten() // Create a new PDF from the filled data const pdfBytes = await pdfDoc.save(); const pickerOpts = { types: [ { description: "PDF Document (.pdf)", accept: { "application/*": [".pdf"], }, }, ], excludeAcceptAllOption: true, multiple: false, }; const fileHandle = await window.showSaveFilePicker(pickerOpts); const fileStream = await fileHandle.createWritable(); // Save the file const blob = new Blob([pdfBytes], { type: 'application/pdf' }); await fileStream.write(blob); await fileStream.close(); } // objects of data to fill const pdf1 = { "number": "1", "name": "John", "phoneNum": "4865138186", } const pdf2 = { "number": "2", "name": "Jane", "phoneNum": "51675469819", } //array that contains the objects const PDFs = [ ["pdf-form",pdf1], ["pdf-form",pdf2] ] // function that starts the process async function processPDF(){ PDFs.forEach(async (element) =>{ await fillPDF(element[0],element[1]) }) } // start function with button press document.getElementById('fillPDF').addEventListener('click', processPDF); </script> </body> </html>
现在的问题是:点击按钮后会弹出多个保存文件的对话框,但只有最后一个保存的文件是正确填充了内容的,前面的文件都是空的。
另外,我希望生成的每个文件都有不同的名称,所以用了系统的保存对话框,但如果有其他更合适的实现方式(比如自动命名并批量下载),也欢迎大家给我提建议,任何相关的指导都非常感谢!
备注:内容来源于stack exchange,提问作者Ricardo Hernández
相关产品推荐
相关产品推荐

