如何将含HTML标签的字符串变量导出为带样式的PDF?
解决方案:将HTML字符串导出为带样式的PDF并支持UTF-8
针对你遇到的问题,以下几种方案可以满足需求:
方案1:升级jsPDF并使用html()方法替代fromHTML
旧版本jsPDF(如你使用的1.4.1)的fromHTML方法存在UTF-8字符支持缺陷,升级到新版后,官方推荐的html()方法对HTML样式解析、字符编码支持更完善。
实现步骤:
- 引入新版jsPDF及依赖的html2canvas:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
- 替换核心代码:
$('#printbutton').click(function () { const { jsPDF } = window.jspdf; const pdf = new jsPDF(); const toPrint = '<b>Hello world! 中文测试</b>'; // 创建临时DOM元素承载HTML内容 const tempDiv = document.createElement('div'); tempDiv.innerHTML = toPrint; document.body.appendChild(tempDiv); // 调用html()方法生成PDF pdf.html(tempDiv, { callback: function(pdf) { pdf.save('helloworld.pdf'); // 清理临时元素 document.body.removeChild(tempDiv); }, x: 10, y: 10 }); });
方案2:html2canvas + jsPDF(复杂HTML样式首选)
如果你的HTML包含复杂布局、自定义CSS样式,html2canvas可将HTML渲染为Canvas,再由jsPDF转为PDF,样式还原度极高,同时完美支持UTF-8字符。
实现代码:
$('#printbutton').click(function () { const toPrint = '<div style="font-size:20px;"><b>Hello world!</b> <span style="color:red;">UTF-8测试:中文、日文(こんにちは)</span></div>'; // 创建隐藏的临时DOM元素 const tempDiv = document.createElement('div'); tempDiv.innerHTML = toPrint; tempDiv.style.visibility = 'hidden'; tempDiv.style.position = 'absolute'; document.body.appendChild(tempDiv); // 渲染为Canvas后生成PDF html2canvas(tempDiv).then(canvas => { const imgData = canvas.toDataURL('image/png'); const pdf = new jsPDF('p', 'mm', 'a4'); const imgWidth = 210; const pageHeight = 297; const imgHeight = canvas.height * imgWidth / canvas.width; let heightLeft = imgHeight; let position = 0; pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight); heightLeft -= pageHeight; // 处理长内容分页 while (heightLeft >= 0) { position = heightLeft - imgHeight; pdf.addPage(); pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight); heightLeft -= pageHeight; } pdf.save('helloworld.pdf'); document.body.removeChild(tempDiv); }); });
方案3:使用pdfmake库
pdfmake是专注PDF生成的工具,配合html-to-pdfmake插件可直接解析HTML片段,原生支持UTF-8字符,无需依赖Canvas。
实现步骤:
- 引入所需CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script> <script src="https://cdn.jsdelivr.net/npm/html-to-pdfmake@2.4.1/dist/html-to-pdfmake.min.js"></script>
- 核心代码:
$('#printbutton').click(function () { const toPrint = '<b>Hello world!</b> <i>UTF-8支持:中文测试</i>'; const docDefinition = { content: htmlToPdfmake(toPrint) }; pdfMake.createPdf(docDefinition).download('helloworld.pdf'); });
以上三种方案均可解决HTML样式识别、UTF-8字符支持问题,可根据你的HTML复杂度选择适配方案。
内容的提问来源于stack exchange,提问作者Faezeh_Ebrahimi
相关产品推荐
相关产品推荐

