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');
  });
};
相关推荐
2301_789015621 小时前
DS进阶:AVL树
开发语言·数据结构·c++·算法
Filotimo_2 小时前
5.3 Internet基础知识
开发语言·php
识君啊2 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
qyzm4 小时前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
leluckys4 小时前
swift- Swift中常见的面试题
开发语言·汇编·swift
BUG_MeDe4 小时前
json格式字符串解析的简单使用 libjson-c
c语言·开发语言·json
唐叔在学习5 小时前
e.preventDefault()到底怎么用?
前端·javascript
CoderCodingNo5 小时前
【GESP】C++五级练习题 luogu-P1182 数列分段 Section II
开发语言·c++·算法
Highcharts.js5 小时前
Highcharts React v4.2.1 正式发布:更自然的React开发体验,更清晰的数据处理
linux·运维·javascript·ubuntu·react.js·数据可视化·highcharts