使用 html2canvas 和 jspdf 将页面转 pdf,同时解决当页面过长时,页面白屏问题

代码如下,直接粘贴复制即可,代码中 jspdf 是全局引入,你可以自己局部引入

别人使用标签的方式来显示 base64,但是当页面过长时,base64 大小过大会导致页面解析异常,显示白屏

ts 复制代码
import html2canvas from 'html2canvas';

export function printPdf(dom: HTMLElement | null) {
  // 1 dom 存在
  if (!dom) return;
  // 2 生成 canvas
  html2canvas(dom, { useCORS: true, allowTaint: true }).then(function (canvas) {
    // document.body.appendChild(canvas);
    // return;
    // 1 canvas 宽高
    const contentWidth = canvas.width;
    const contentHeight = canvas.height;
    console.log('contentWidth contentHeight', contentWidth, contentHeight);

    // 2 一页 pdf 显示 html 页面生成的 canvas 高度
    const pageHeight = (contentWidth / 592.28) * 841.89;
    // 3 未生成 pdf 的 html 页面高度
    let leftHeight = contentHeight;
    // 4 pdf 页面偏移
    let position = 0;
    // 5 a4纸的尺寸 [595.28, 841.89],html 页面生成的 canvas 在 pdf 中图片的宽高
    const imgWidth = 595.28;
    const imgHeight = (592.28 / contentWidth) * contentHeight;
    const img = canvas.toDataURL('image/jpeg', 1.0);
    const pdf = new jspdf.jsPDF('', 'pt', 'a4');
    // 有两个高度需要区分,一个是html页面的实际高度,和生成 pdf 的页面高度(841.89)
    // 当内容未超过 pdf 一页显示的范围,无需分页
    if (leftHeight < pageHeight) {
      pdf.addImage(img, 'JPEG', 0, 0, imgWidth, imgHeight);
    } else {
      while (leftHeight > 0) {
        console.log(imgWidth, imgHeight, position, leftHeight);
        pdf.addImage(img, 'JPEG', 0, position, imgWidth, imgHeight);
        leftHeight -= pageHeight;
        position -= 841.89;
        // 避免添加空白页
        if (leftHeight > 0) {
          pdf.addPage();
        }
      }
    }
    // 6 挂载至页面
    const blob = dataURLtoBlob(pdf.output('datauristring'));
    console.log(blob);
    const url = window.URL.createObjectURL(blob); //获得一个pdf的url对象
    location.href = url;
    // window.open(url, '_blank')//打开一个新窗口
    // console.log(url);
    // URL.revokeObjectURL(url) //释放内存
    // const base64String = btoa(pdf.output());
    // const embed = `<embed type="application/pdf" src="data:application/pdf;base64, ${base64String}" width="100%" height="100%">`;
    // document.documentElement.style.overflow = 'hidden';
    // document.body.innerHTML = embed;
  });
}
相关推荐
CopyCode2 分钟前
我排查了一下午,发现项目打包体积翻倍的元凶是它
前端·性能优化
u01110267511 分钟前
Vue 3 实现图片裁剪框:拖动、缩放与固定宽高比
前端·javascript·vue.js
泡海椒25 分钟前
多维数据分析:jquick-pdf 热力图、雷达图 PDF 实战
数据挖掘·数据分析·pdf
汉堡大王952732 分钟前
一张图三句需求,我用 Trae Work 做了一块能看日出日落和月相的天文机械表
前端·后端·github
小小善后师42 分钟前
用 Canvas + AI 实现登录页的 Logo 粒子动画
前端·vue.js
Amos_Web42 分钟前
Rspack 源码解析(十六):多类型资源如何进入 Compilation.assets
前端·rust·前端框架
GAMC44 分钟前
chrome-devtools-mcp:让 AI 编码助手真正"看见"浏览器
前端·人工智能
deli0071 小时前
高尔顿板:把球一颗颗丢下去,为什么最后总堆成一座钟形山
前端
java_nnnn1 小时前
JavaEE进阶-CSS初识
java·前端·css·java-ee·html
good_ideal1 小时前
从零实现一个自动提交 PR 的 MCP 工具:用 Skill 串起 Git 与 Azure DevOps
前端