使用 html2canvas + jspdf 实现页面元素下载为pdf文件
使用 html2canvas + jspdf 实现页面元素下载为pdf文件
准备
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
js文件可以用在线文件,但是在工作环境中,最后下载下来保存到本地。
页面元素信息
我们需要给定一个 html 的元素,用id标注,方便js获取
<div id="pdfArea"><table><tr><th>姓名</th><th>年龄</th></tr><tr><td>张三</td><td>25</td></tr></table>
</div><button onclick="downloadPDF()">下载 PDF</button>
js相关
js相关代码逻辑,已支持pdf待白边,更美观
function downloadPDF() {const { jsPDF } = window.jspdf;const element = document.getElementById("pdfArea");html2canvas(element, {scale: 2,useCORS: true}).then(canvas => {const imgData = canvas.toDataURL("image/png");const pdf = new jsPDF("p", "mm", "a4");const pageWidth = pdf.internal.pageSize.getWidth(); // 210const pageHeight = pdf.internal.pageSize.getHeight(); // 297const margin = 15; // 白边宽度(mm)const imgWidth = pageWidth - margin * 2;const imgHeight = (canvas.height * imgWidth) / canvas.width;let heightLeft = imgHeight;let position = margin; // 起始 Y 坐标(顶部白边)pdf.addImage(imgData, "PNG", margin, position, imgWidth, imgHeight);heightLeft -= pageHeight - margin * 2;while (heightLeft >= 0) {position = heightLeft - imgHeight + margin;pdf.addPage();pdf.addImage(imgData, "PNG", margin, position, imgWidth, imgHeight);heightLeft -= pageHeight - margin * 2;}pdf.save("文件名.pdf");});
}