html2pdf生成PDF后btoa函数转换Base64异常问题排查
问题分析与解决方案
你遇到的问题根源在于html2pdf链式调用中save()方法的then回调并没有传递PDF的二进制数据,导致你拿到的pdf参数是undefined——而btoa(undefined)会把undefined转成字符串"undefined",它的Base64编码正好就是你看到的dW5kZWZpbmVk。
为什么会这样?
html2pdf的save()方法是一个终端操作,它的作用是触发浏览器下载PDF,并不会在后续的then回调中返回生成的PDF数据。你需要先通过outputPdf()获取到PDF的原始二进制数据(Uint8Array类型),再进行Base64编码和保存操作。
修正后的代码
html2pdf().from(element).set(opt).outputPdf().then(function(pdfUint8Array) { // 将Uint8Array转换为可被btoa处理的字符串 const pdfString = String.fromCharCode(...pdfUint8Array); // 编码为Base64 const newpdf = btoa(pdfString); console.log(newpdf); // 现在会输出完整的Base64字符串 // 触发PDF下载(如果需要的话) html2pdf().from(element).set(opt).save(); // 发送到后端接口 $.post('./setup', {payload: newpdf}, function(result) { console.log('done'); }); });
关键细节说明
outputPdf()的返回值:它返回的Promise会resolve一个Uint8Array类型的二进制数据,这是PDF的原始字节流。- Uint8Array转字符串:
btoa()只能处理ASCII字符串,所以需要用String.fromCharCode(...pdfUint8Array)把字节数组转成对应的字符串,再进行Base64编码。 - 优化下载逻辑(可选):如果不想重复生成PDF,可以用获取到的
Uint8Array自行创建Blob触发下载,避免重复渲染开销:// 用获取到的Uint8Array创建下载链接 const blob = new Blob([pdfUint8Array], {type: 'application/pdf'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'document.pdf'; a.click(); URL.revokeObjectURL(url);
这样修改后,你就能得到完整的Base64字符串并成功发送到后端了。
内容的提问来源于stack exchange,提问作者jedu
相关产品推荐
相关产品推荐

