React项目中如何使用html2pdf.js生成PDF File对象并上传至Google Drive
html2pdf.js 直接获取PDF File对象实现方案
原代码的核心问题是html2pdf的转换流程为异步操作,同步调用output()无法获取到真实的PDF内容,不需要手动调用toContainer()/toCanvas()等中间方法,库内部会自动完成全链路转换,正确实现代码如下:
推荐async/await写法(适配React异步逻辑)
async function createPDF() { console.log('create PDF function works!'); const element = document.getElementById('report_component'); const opt = { margin: 1, filename: 'my-invoice.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2 }, jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' } }; // 等待异步转换完成,直接输出blob格式内容 const pdfBlob = await window.html2pdf().set(opt).from(element).output('blob'); // 转换为标准File对象,可直接用于Google Drive上传 const pdfFile = new File([pdfBlob], 'my-invoice.pdf', { type: 'application/pdf' }); // 此处编写后续上传Google Drive的逻辑 console.log(pdfFile); }
备选Promise.then写法
function createPDF() { console.log('create PDF function works!'); const element = document.getElementById('report_component'); const opt = { margin: 1, filename: 'my-invoice.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2 }, jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' } }; window.html2pdf().set(opt).from(element).output('blob') .then(pdfBlob => { const pdfFile = new File([pdfBlob], 'my-invoice.pdf', { type: 'application/pdf' }); // 此处编写后续上传Google Drive的逻辑 console.log(pdfFile); }) }
关键注意点
- 必须等待异步转换完成后再处理PDF内容,同步调用获取到的只是未完成的Promise实例,无法生成可用的PDF文件
- 调用
output('blob')指定输出格式为blob,不需要手动调用中间转换方法,避免流程出错 - 生成的
pdfFile为标准W3C File实例,完全适配Google Drive上传接口的参数要求
内容的提问来源于stack exchange,提问作者Dhanusha_Perera07
相关产品推荐
相关产品推荐

