JS-页面截图下载为pdf

发布于:2024-06-20 ⋅ 阅读:(73) ⋅ 点赞:(0)

这个需要两个 js 库支持,html2canvas 和 jspdf。

下载:
npm install html2canvas --save
npm install jspdf–save
引用:
import { jsPDF } from ‘jspdf’;
import html2canvas from ‘html2canvas’;

直接上代码:

const downloadPDF = () => {
  const element: any = document.querySelector('.app');
  // const { scrollHeight, scrollWidth, offsetHeight, height } = element;
  const opts = {
    scale: 3, // 缩放比例,提高生成图片清晰度
    useCORS: true, // 允许加载跨域的图片
    allowTaint: false, // 允许图片跨域,和 useCORS 二者不可共同使用
    tainttest: true, // 检测每张图片都已经加载完成
    logging: true, // 日志开关,发布的时候记得改成 false
    height: element.offsetHeight
  };
  html2canvas(element, opts).then((canvas) => {
    let contentWidth = canvas.width;
    let contentHeight = canvas.height;
    let pageHeight = contentWidth / 592.28 * 841.89 - 40;
    let leftHeight = contentHeight;
    let position = 20;
    let imgWidth = 570;
    let imgHeight = 592.28 / contentWidth * contentHeight;
    let pageData = canvas.toDataURL('image/jpeg', 1.0);
    let PDF = new jsPDF('p', 'pt', 'a4');
    if (leftHeight < pageHeight) {
      PDF.addImage(pageData, 'JPEG', 14, 20, imgWidth, imgHeight);
    } else {
      while (leftHeight > 0) {
        PDF.addImage(pageData, 'JPEG', 14, position, imgWidth, imgHeight);
        leftHeight -= pageHeight;
        position -= 841.89;
        if (leftHeight > 0) {
          PDF.addPage();
        }
      }
    }
    PDF.save(2222 + '.pdf');
  });
};

网站公告

今日签到

点亮在社区的每一天
去签到