使用 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获取

html 复制代码
<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待白边,更美观

js 复制代码
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();   // 210
    const pageHeight = pdf.internal.pageSize.getHeight(); // 297

    const 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");
  });
}
相关推荐
happy_0x3f2 分钟前
前端应用的离线暂停更新策略
开发语言·前端·php
审小匠OpenCPAi19 分钟前
审计票据与财报 PDF 怎么识别?通用 OCR、表格结构识别与多模态大模型的精度对比
pdf·ocr·审计
你驴我39 分钟前
WhatsApp 消息撤回与编辑的幂等性设计实践
java·服务器·前端·后端·python
2501_930707781 小时前
使用C#代码将 PDF 文件转换为 Markdown 格式
pdf
新中地GIS开发老师1 小时前
零基础WebGIS开发入门 | GeoJSON数据持久化
前端·javascript·gis·webgis·三维gis开发
blns_yxl1 小时前
正则驱动实时表单验证(HTML+CSS+JS+正则)
javascript·css·html
sunywz2 小时前
【c#】 Web Deploy一键发布,IIS部署全流程
开发语言·前端·c#
宁&沉沦2 小时前
Chrome 扩展 Manifest 字段版本支持一览(全量)
前端·后端·编辑器
乖孩子2 小时前
Service Worker + IndexedDB 实践
前端
浮生望2 小时前
BFF架构实战:用Express+SSE为Vue3搭建安全的流式对话中间层
前端