html2canvas将页面绘制图片使用jspdf导出

该代码示例展示了如何使用html2canvas将HTML内容转化为canvas,然后利用jspdf库将canvas内容保存为A4大小的PNG图像并生成PDF文件,点击按钮即可下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

粗略实现导出,细节后续再补充。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./js/html2canvas.js"></script>
  <script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
</head>

<body>
  <div id="root">
    <h3>名片</h3>
    <div class="person">
      <img style="width: 600px; height: 400px;"
        src="https://img0.baidu.com/it/u=3976250177,3245140550&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=675" alt="">
    </div>
  </div>
  <button id="downloadImg">点击</button>
</body>

<script >
 const {jsPDF} = jspdf
  let dom = document.getElementById("downloadImg");
  dom.onclick = function () {
    // 实现保存为图片的第一步:html转为canvas
    html2canvas(document.getElementById("root"), {
      useCORS: true,
      scale: window.devicePixelRatio,
      height: 600,
      width: 800,
      // backgroundColor: null
    }).then(function (canvas) {
      const contentWidth = canvas.width;
      const contentHeight = canvas.height;

      let dataImg = canvas.toDataURL();
      console.log('content',contentWidth,contentHeight);
      //方向默认竖直,尺寸ponits,横向l
      //格式a4[595.28,841.89], 单位pt
      var doc = new jsPDF('p', 'mm', [210,297])

      doc.addImage(dataImg, 'PNG', 10, 10, 210, 297);
      doc.save('a4.pdf');

    });
  }
</script>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值