如何用html2pdf存储Base64格式PDF至变量?Google Apps Script调用异常排查
问题分析与解决方案
核心问题
- 异步执行顺序错误:html2pdf的
outputPdf().then()是异步操作,你当前在then()外部调用google.script.run.savePdf()时,PDF还未生成,file变量仍是初始空字符串,导致保存的文件内容为空。 - 过早终止上下文:如果在
then()内部调用savePdf()后直接执行window.print()和google.script.host.close(),会因为google.script.run本身也是异步操作,窗口提前关闭导致服务器端请求被中断,日志显示方法未执行。 - PDF数据处理不当:直接对
outputPdf()返回的结果使用btoa()可能因数据类型不匹配(比如返回的是Uint8Array而非字符串),导致传递给服务器的内容无效。
修正后的代码
function savefile() { var element = document.getElementById("pgBody"); var poNumber = document.getElementById('fabricPo').value; var supplier = document.getElementById('selectSupplier').value; let fileName = supplier + " - " + poNumber + ".pdf"; var opt = { margin: [2, 5, 2, 5], //top, left, bottom, right filename: fileName, image: { type: "jpeg", quality: 0.98, }, html2canvas: { scale: 2, }, jsPDF: { unit: "mm", orientation: "landscape", }, }; html2pdf() .set(opt) .from(element) .outputPdf() .then(function (pdfData) { // 处理PDF数据:将Uint8Array转为base64字符串 let base64Pdf; if (pdfData instanceof Uint8Array) { const binary = String.fromCharCode(...pdfData); base64Pdf = btoa(binary); } else { base64Pdf = btoa(pdfData); } // 调用服务器端方法,添加回调确保操作完成后再执行后续步骤 google.script.run .withSuccessHandler(function() { window.print(); google.script.host.close(); }) .withFailureHandler(function(error) { console.error("保存PDF失败:", error); // 可选:失败后的提示逻辑 }) .savePdf(base64Pdf, fileName); }); }
关键改动说明
- 调整异步执行顺序:将
google.script.run完全移入then()回调内,确保只有在PDF生成完成后才触发保存操作。 - 正确转换PDF数据:判断
outputPdf()返回的pdfData类型,若为Uint8Array则先转为二进制字符串再做base64编码,避免数据格式错误。 - 添加异步回调:使用
withSuccessHandler和withFailureHandler,确保服务器端保存操作完成后再执行打印和窗口关闭,避免请求被中断。 - 移除无效变量赋值:删除了原本的空
file变量,直接在回调内处理生成的PDF数据,减少不必要的变量传递。
内容的提问来源于stack exchange,提问作者onit
相关产品推荐
相关产品推荐

