其他分享
首页 > 其他分享> > 使用jspdf和html2canvas将当前网页保存为pdf

使用jspdf和html2canvas将当前网页保存为pdf

作者:互联网

首先引入组件

import { jsPDF } from "jspdf";
import html2canvas from 'html2canvas';

将当前页面保存为pdf,有两种处理方式,一种分页,一直分页

不分页:

// 滚动到顶部,避免打印不全
      document.getElementById("pdfcontent").scrollTop = 0;
      //设置放大倍数会存在问题,后面的不少图片会丢失/最后的文字会被截断
      var scale = 2;
      html2canvas(document.getElementById("pdfcontent"), {
        allowTaint: true,
        scale: scale,//放大倍数
        dpi: 300,
      }).then(function (canvas) {
        //画布大小
        let contentWidth = canvas.width;
        let contentHeight = canvas.height;

        // 将canvas转为base64图片
        var pageData = canvas.toDataURL('image/jpeg', 1.0);

        // 设置pdf的尺寸,pdf要使用pt单位 已知 1pt/1px = 0.75   pt = (px/scale)* 0.75
        var pdfWidth = (contentWidth + 10) / 2 * 0.75;
        var pdfHeight = (contentHeight + 500) / 2 * 0.75;

        // 设置内容图片的尺寸,img是pt单位 
        var imgWidth = pdfWidth;
        var imgHeight = (contentHeight / 2 * 0.75);

        //初始化jspdf 第一个参数方向:默认''时为纵向,第二个参数设置pdf内容图片使用的长度单位为pt,第三个参数为PDF的大小,单位是pt
        const PDF = new jsPDF('', 'pt', [pdfWidth, pdfHeight]);

        PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
        PDF.save('test.pdf');
      })

分页

html2canvas(document.getElementById("pdfcontent"), {
        allowTaint: true,
        height: document.getElementById("pdfcontent").scrollHeight,//
        width: document.getElementById("pdfcontent").scrollWidth//为了使横向滚动条的内容全部展示,这里必须指定
      }).then(function (canvas) {
        let contentWidth = canvas.width;
        let contentHeight = canvas.height;
        //一页pdf显示html页面生成的canvas高度;
        let pageHeight = contentWidth / 595.28 * 841.89;
        //未生成pdf的html页面高度
        let leftHeight = contentHeight;
        //pdf页面偏移
        let position = 0;
        //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
        let imgWidth = 595.28;
        let imgHeight = 595.28 / contentWidth * contentHeight;
        let pageData = canvas.toDataURL('image/jpeg', 1.0);
        let PDF = new jsPDF('', 'pt', 'a4');
        //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
        //当内容未超过pdf一页显示的范围,无需分页
        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight);
        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight);
            leftHeight -= pageHeight;
            position -= 841.89;
            if (leftHeight > 0) {
              PDF.addPage();
            }
          }
        }
        PDF.save('test.pdf');
      })

这两种方式都有坑

标签:jspdf,canvas,pt,html2canvas,let,pdf,PDF,contentHeight
来源: https://www.cnblogs.com/wanggang2016/p/15155344.html