使用 html2canvas 生成 分页的PDF(直接用)

本文介绍了一种使用html2canvas和jsPDF将网页内容转换为PDF文件的方法。通过示例代码展示了如何捕获网页的渲染内容,并将其转化为PDF格式,特别适用于需要保存或分享网页布局的场景。

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

直接上代码

<!DOCTYPE>
<html>
  <head>
    <title>
      html2canvas example
    </title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      body {
        margin: 0;
        padding: 0;
        background-color: white;
      }
      header, section {
          overflow: hidden;
      }
      ul {
        margin: 0;
        border: 0;
        padding: 0;
      }
      li {
        display: block; /* i.e., suppress marker */
        color: black;
        height: 4em;
        width: 25%;
        margin: 0;
        float: left;
        background-color: green;
        text-align: center;
        line-height: 4em;
      }
      
      aside {
        width: 20%;
        float: left;
        text-align: center;
      }

      aside a {
        display: block;
        height: 4em;
        color: blue;
      }

      article {
        padding: 2em 0;
        width: 80%;
        float: left;
      }
    </style>
  </head>
  <body>
  <button id="renderPdf">打印</button>
  <div id="storeBox">
      <!--<img src="./img/Stone.png">
      <h2>Stone Giant</h2>
      <p>
          Coming to life as a chunk of stone, Tiny's origins are a mystery on which he continually speculates. He is a Stone Giant now, but what did he used to be? A splinter broken from a Golem's heel? A shard swept from a gargoyle-sculptor's workshop? A fragment of the Oracular Visage of Garthos? A deep curiosity drives him, and he travels the world tirelessly seeking his origins, his parentage, his people. As he roams, he gathers weight and size; the forces that weather lesser rocks, instead cause Tiny to grow and ever grow.
      </p>
      <p>
          以一团石头的形式出现的生命体,小小不断思索他的起源,但这始终是个谜。现在的他是个石巨人,但过去是什么呢?从土傀儡的脚后跟掉落的碎片?从制造石像鬼的工房被打扫出来的碎屑?神圣预言石的表层之砂?受到强烈的好奇心驱使,他不知疲倦的环游世界,寻找着他的起源,他的出身,和他的种族。在旅途中,他变得越来越庞大,不过路上的风雨吹打掉了他身上的石头,所以他不停的吸收新的岩石,永远在长大。
      </p>-->
  </div>
    <script type="text/javascript" src="./js/html2canvas.js"></script>
    <script type="text/javascript" src="./js/jsPdf.debug.js"></script>
    <script type="text/javascript" src="./js/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
          $.ajax({
              url: 'https://testing.snaily.com.cn/v1/home?page=1&size=10',
              method: 'get',
              data: '',
              success: function(res) {
                  var that = this
                  console.log(JSON.parse(res))
                  that.testDate = JSON.parse(res).data
                  var storeContent = ''
                  for (var i = 0; i< that.testDate.length; i++) {
                      storeContent += '<img src="' + that.testDate[i].avatarurl + '">'
                          +'<div>'+ that.testDate[i].home_title +'</div>'
                          +'<div>'+ that.testDate[i].notes +'</div>'
                          +'<div>'+ that.testDate[i].title +'</div>'
                  }
                  $("#storeBox").html(storeContent)
              }
          })
      })
     var downPdf = document.getElementById("renderPdf");
      downPdf.onclick = function() {
          html2canvas(document.body, {
              useCORS: true, // 设置为true  可以使用网络图片,不然就要使用绝对路径的图片
              onrendered:function(canvas) {
                  var contentWidth = canvas.width;
                  var contentHeight = canvas.height;

                  //一页pdf显示html页面生成的canvas高度;
                  var pageHeight = contentWidth / 592.28 * 841.89;
                  //未生成pdf的html页面高度
                  var leftHeight = contentHeight;
                  //pdf页面偏移
                  var position = 0;
                  //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
                  var imgWidth = 595.28;
                  var imgHeight = 592.28/contentWidth * contentHeight;

                  var pageData = canvas.toDataURL('', 2.0);

                  var pdf = new jsPDF('', 'pt', 'b4');

                  //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
                  //当内容未超过pdf一页显示的范围,无需分页
                  if (leftHeight < pageHeight) {
                      pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
                  } else {
                      while(leftHeight > 0) {
                          pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                          leftHeight -= pageHeight;
                          position -= 841.89;
                          //避免添加空白页
                          if(leftHeight > 0) {
                              pdf.addPage();
                          }
                      }
                  }
                  pdf.save('Diary.pdf');
              }
          })
      }
    </script>
  </body>
</html>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值