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`);
  });
};
相关推荐
无糖可可果25 分钟前
从零读懂一个 Next.js 全栈笔记应用
前端
Maxkim25 分钟前
DeepSeek Harness 源码深度分析:像 VS Code 一样插件化的 Agent 框架
前端·架构
喜欢睡觉30 分钟前
从零看懂一个 Next.js 笔记应用
前端
cindershade32 分钟前
从零实现画布「双击创建节点」:一个 VueFlow 项目的交互全记录
前端
YHL32 分钟前
🚀 SSE 服务器发送事件与 BFF 层实战
前端·后端
今日无bug34 分钟前
HTML5 Canvas:从画图到游戏开发
前端·canvas
cindershade36 分钟前
用 Web Workers 优化前端重计算任务:避免主线程卡顿的实战方案
前端
爱丶不疚36 分钟前
搞不清 CommonJS 与 ESM,你是否也有这些疑问🤔
前端·node.js
YIAN41 分钟前
http无状态?State来展示!从基础路由到鉴权守卫,吃透 SPA 前端路由核心
前端·react.js
__zRainy__1 小时前
Node系列 · Node基础:全局变量与全局对象
开发语言·前端·javascript