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');
  });
};
相关推荐
折哥的程序人生 · 物流技术专研3 小时前
第3篇:为何要配置环境变量?
java·开发语言·后端·面试
游乐码4 小时前
c#迭代器
开发语言·c#
十五年专注C++开发4 小时前
Qt程序设计涉及到的开发软件
开发语言·c++·qt
海盗12344 小时前
C# OPC UA客户端开发实战
服务器·开发语言·c#
asdzx674 小时前
使用 C# 从 URL 下载 Word 文档
开发语言·c#·word
大萌神Nagato4 小时前
python 包管理器uv
开发语言·python·uv
Hello--_--World4 小时前
Vue:虚拟Dom
前端·javascript·vue.js
humcomm4 小时前
AI 编程时代-全栈开发技术栈解析
开发语言·人工智能
人道领域4 小时前
【黑马点评日记】社交平台用户关注功能全解析Feed流相关操作
java·开发语言·数据库·redis·python
xiaoshuaishuai85 小时前
C# DeepSeek V4 与 V3对比
开发语言·c#·量子计算