使用 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");
  });
}
相关推荐
程序员爱钓鱼1 小时前
Go操作Excel实战详解:github.com/xuri/excelize/v2
前端·后端·go
子兮曰9 小时前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭9 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路12 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒13 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
Kagol14 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉14 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau14 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生14 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼14 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范