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`);
  });
};
相关推荐
hu5566798几秒前
Adobe Acrobat DC PDF如何批量文本替换
adobe·pdf
向日葵同志44330几秒前
使用@univerjs纯前端渲染excel, 显示图片、链接、样式
前端·react.js·excel
可别39013 分钟前
使用Worker打包报错
前端·vue.js
GIS瞧葩菜17 分钟前
【无标题】
开发语言·前端·javascript·cesium
T___T23 分钟前
彻底搞懂 CSS 盒子模型 box-sizing:小白也能看懂的布局核心
前端·面试
彭于晏爱编程26 分钟前
关于表单,别做工具库舔狗
前端·javascript·面试
空白格9726 分钟前
Android插件化开发
前端
风中凌乱的L28 分钟前
vue canvas标注
前端·vue.js·canvas
拉不动的猪29 分钟前
什么是二义性,实际项目中又有哪些应用
前端·javascript·面试
海云前端131 分钟前
Webpack打包提速95%实战:从20秒到1.5秒的优化技巧
前端