html2canvas实现js下载html页面

安装

npm install html2canvas

下载

//引入
import html2canvas from 'html2canvas';

//根据divId截图
html2canvas(document.getElementById(divId), {//这是配置项
    backgroundColor: '#f1f5f8',//设置背景色
    scale: 3,
    height: document.getElementById(divId).scrollHeight,//出现滚动条时截取长图
    windowHeight: document.getElementById(divId).scrollHeight,//出现滚动条时截取长图
  }).then(function (canvas) {
    const pngData = canvas.toDataURL('image/png');//转换成png
    const filename = `${name}.png`;
    //实现js下载
    const anchor = document.createElement('a');
    anchor.href = data;
    anchor.download = filename;
    anchor.click()
  });

下载成PDF

import jsPDF from 'jspdf';
import { applyPlugin } from 'jspdf-autotable';
applyPlugin(jsPDF);
import html2canvas from 'html2canvas';

const height = document.getElementById(divId).scrollHeight;
  html2canvas(document.getElementById(divId), {
    backgroundColor: '#f1f5f8',
    scale: 3,
    height: height,
    windowHeight: height,
  }).then(function (canvas) {
    const pngData = canvas.toDataURL('image/jpeg', 1.0);
    const doc = new jsPDF('p', 'pt', 'a4');
    const aWidth = 595.28;
    const aHeight = 841.89;
    const pageHeight = (aHeight * canvas.width) / aWidth;
    const imgHeight = (aWidth * canvas.height) / canvas.width;
    let leftHeight = canvas.height;
    let position = 0;
    while (leftHeight > 0) {//高度超出A4纸高度时,需要遍历
      doc.addImage(pngData, 'JPEG', 0, position, aWidth, imgHeight);
      leftHeight -= pageHeight;
      position -= aHeight;
      if (leftHeight > 0) {//增加页面
        doc.addPage();
      }
    }
    doc.save(`${filename}.pdf`);
  });

文档

html2canvas配置项文档链接

你可能感兴趣的:(前端,javascript,html,前端)