React 将页面导出为pdf

安装依赖包

npm i --save html2canvas
npm i --save jspdf

使用 

一个ref也可以,我这里是多个元素导出多个页面 

  const ref1 = useRef<HTMLDivElement>(null);
  const ref2 = useRef<HTMLDivElement>(null);
  const refs = [ref1, ref2];
  const handleExportPdf = async () => {
    // 根据dpi放大,防止图片模糊
    const scale = window.devicePixelRatio > 1 ? window.devicePixelRatio : 2;
    // 下载尺寸 a4 纸 比例
    const pdf = new jsPDF('p', 'pt', 'a4')
    for(let i in refs){
      const toPdfRef = refs[i];
      let width = toPdfRef.current.offsetWidth;
      let height = toPdfRef.current.offsetHeight;
  
      const canvas = document.createElement('canvas');
      canvas.width = width * scale;
      canvas.height = height * scale;
      const pdfCanvas = await html2canvas(toPdfRef.current, {
        useCORS: true,
        canvas,
        scale,
        width,
        height,
        x: 0,
        y: 0,
      });
      const imgDataUrl = pdfCanvas.toDataURL();

      if(height > 14400){ // 超出jspdf高度限制时
        const ratio = 14400 / height;
        height = 14400;
        width = width * ratio;
      }

      // 缩放为 a4 大小  pdfpdf.internal.pageSize 获取当前pdf设定的宽高
      height = height * pdf.internal.pageSize.getWidth() / width;
      width = pdf.internal.pageSize.getWidth();
  
      // pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置
      pdf.addImage(imgDataUrl, 'png', 0, 0, width, height)

      // 若当前是最后一张截图,则不再另起一页,直接退出循环
      if(+i >= refs.length - 1){
        break;
      }

      // 另起一页
      pdf.addPage();
    }

    // 导出下载 
    await pdf.save("pdf名", { returnPromise: true });
  }

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值