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`);
  });
};
相关推荐
菜鸟小芯4 分钟前
【GLM-5 陪练式前端新手入门】第四篇:卡片布局 —— 让个人主页内容更有层次
前端·人工智能
Hello.Reader10 分钟前
Leptos + Tauri 2 前端配置Trunk + SSG + 移动端热重载一次打通(Leptos 0.6 口径)
前端
岱宗夫up17 分钟前
【前端基础】HTML + CSS + JavaScript 进阶(一)
开发语言·前端·javascript·css·html
qq_242188633230 分钟前
【零基础使用Trae CN编写第一个AI游戏教程】
开发语言·前端·人工智能·python·游戏·html
a11177632 分钟前
3D赛车躲避游戏(html threeJS开源)
前端·游戏·3d·开源·html·threejs
PD我是你的真爱粉35 分钟前
Vue Router 4 路由进阶
前端·javascript·vue.js
木子欢儿37 分钟前
在 Debian 13(以及 12)上安装和配置 tightvncserver 并让普通用户使
运维·前端·debian
SakitamaX1 小时前
Nginx安装与实验
服务器·前端·nginx
软件资深者1 小时前
2026 版初中几何辅助线教材 PDF|打印即提分,中考几何 “分水岭” 一键通关
学习·数学·pdf·教学·初中数学
用户新1 小时前
V8引擎 精品漫游指南--Ignition篇(中) AST详解 字节码的生成
前端·javascript