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`);
  });
};
相关推荐
疯狂动物城在逃flash4 分钟前
数据库入门:SQL学习路线图与实战技巧
前端
前端小巷子9 分钟前
跨域问题解决方案:开发代理
前端·javascript·面试
前端_逍遥生10 分钟前
Chrome 插件开发到发布完整指南:从零开始打造 TTS 朗读助手
前端·chrome
Mintopia10 分钟前
Three.js 材质与灯光:一场像素级的光影华尔兹
前端·javascript·three.js
天涯学馆11 分钟前
JavaScript 跨域、事件循环、性能优化面试题解析教程
前端·javascript·面试
掘金一周20 分钟前
别再用 100vh 了!移动端视口高度的终极解决方案| 掘金一周7.3
前端·后端
晴殇i22 分钟前
CSS 迎来重大升级:Chrome 137 支持 if () 条件函数,样式逻辑从此更灵活
前端·css·面试
咚咚咚ddd24 分钟前
cursor mcp实践:网站落地页性能检测报告(browser-tools)
前端
MiyueFE25 分钟前
让我害怕的 TypeScript 类型 — — 直到我学会了这 3 条规则
前端·typescript
Hilaku25 分钟前
2025年,每个前端都应该了解的CSS选择器:`:has()`, `:is()`, `:where()`
前端·css