JS-页面截图下载为pdf

这个需要两个 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');
  });
};
相关推荐
Mr_Xuhhh12 小时前
YAML相关
开发语言·python
咖啡の猫12 小时前
Python中的变量与数据类型
开发语言·python
前端达人12 小时前
你的App消息推送为什么石沉大海?看Service Worker源码我终于懂了
java·开发语言
汤姆yu12 小时前
基于springboot的电子政务服务管理系统
开发语言·python
云中飞鸿13 小时前
函数:委托
javascript
全栈师13 小时前
C#中控制权限的逻辑写法
开发语言·c#
S***q19213 小时前
Rust在系统工具中的内存安全给代码上了三道保险锁。但正是这种“编译期的严苛”,换来了运行时的安心。比如这段代码:
开发语言·后端·rust
打点计时器13 小时前
matlab 解决wfdb工具使用本地数据集报错
开发语言·matlab
zmzb010313 小时前
C++课后习题训练记录Day38
开发语言·c++
夏霞13 小时前
c# 使用vs code 创建.net8.0以及.net6.0 webApi项目的教程
开发语言·c#·.net