React网页转换为pdf并下载|使用jspdf html2canvas

checkout 分支后突然报错,提示:

Can't resolve 'jspdf' in ...

Can't resolve 'html2canvas' in ...

解决方法很简单,重新 yarn install 就好了,至于为什么,我暂时也不知道,总之解决了。

思路来源:

先随便记一下写的js,将组件转换为pdf,添加水印,并且下载:

javascript 复制代码
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

/**
 * 导出PDF
 * @param {导出后的文件名} filename
 * @param {要导出的dom节点} dom
 * @param {导出的文件水印:用户邮箱} email
 */

export const exportPDF = (filename, dom, email) => {
  const scale = 0.8;

  // 滚动到顶部,避免打印不全
  document.documentElement.scrollTop = 0;

  html2canvas(dom, {
    allowTaint: true, // Whether to allow cross-origin images to taint the canvas
    scale, // The scale to use for rendering. Defaults to the browsers device pixel ratio.
  }).then((canvas) => {
    const contentWidth = canvas.width / scale;
    const contentHeight = canvas.height / scale;
    console.log(
      "height",
      contentHeight,
      canvas.height,
      contentWidth,
      canvas.width,
      dom.offsetWidth,
      dom.offsetHeight,
    );
    const pdf = new jsPDF("", "pt", [contentWidth, contentHeight]);
    const pageData = canvas.toDataURL("image/jpeg", 1.0);

    pdf.addImage(
      pageData,
      "JPEG",
      (contentWidth - contentWidth / 2.6) / 2, // x偏移
      20, // y偏移
      contentWidth / 2.6,
      contentHeight > 14400 ? 14380 : contentHeight,
      "",
      "FAST"
    );

    // 添加水印
    for (let i = 1; i < contentHeight / 240 - 1; i++) {
      pdf.setTextColor(150);
      pdf.setFontSize(35);
      pdf.setFont("courier");
      pdf.text(contentWidth / 2, 450 * i, email, 45);
    }

    pdf.save(`${filename}.pdf`);
  });
};
相关推荐
LuckyLay1 小时前
React百日学习计划——Deepseek版
前端·学习·react.js
gxn_mmf1 小时前
典籍知识问答重新生成和消息修改Bug修改
前端·bug
hj10431 小时前
【fastadmin开发实战】在前端页面中使用bootstraptable以及表格中实现文件上传
前端
乌夷1 小时前
axios结合AbortController取消文件上传
开发语言·前端·javascript
晓晓莺歌2 小时前
图片的require问题
前端
码农黛兮_462 小时前
CSS3 基础知识、原理及与CSS的区别
前端·css·css3
水银嘻嘻3 小时前
web 自动化之 Unittest 四大组件
运维·前端·自动化
(((φ(◎ロ◎;)φ)))牵丝戏安3 小时前
根据输入的数据渲染柱形图
前端·css·css3·js
wuyijysx3 小时前
JavaScript grammar
前端·javascript
溪饱鱼3 小时前
第6章: SEO与交互指标
服务器·前端·microsoft