使用 html2canvas 和 jspdf 将页面转 pdf,同时解决当页面过长时,页面白屏问题

代码如下,直接粘贴复制即可,代码中 jspdf 是全局引入,你可以自己局部引入

别人使用标签的方式来显示 base64,但是当页面过长时,base64 大小过大会导致页面解析异常,显示白屏

import html2canvas from 'html2canvas';

export function printPdf(dom: HTMLElement | null) {
  // 1 dom 存在
  if (!dom) return;
  // 2 生成 canvas
  html2canvas(dom, { useCORS: true, allowTaint: true }).then(function (canvas) {
    // document.body.appendChild(canvas);
    // return;
    // 1 canvas 宽高
    const contentWidth = canvas.width;
    const contentHeight = canvas.height;
    console.log('contentWidth contentHeight', contentWidth, contentHeight);

    // 2 一页 pdf 显示 html 页面生成的 canvas 高度
    const pageHeight = (contentWidth / 592.28) * 841.89;
    // 3 未生成 pdf 的 html 页面高度
    let leftHeight = contentHeight;
    // 4 pdf 页面偏移
    let position = 0;
    // 5 a4纸的尺寸 [595.28, 841.89],html 页面生成的 canvas 在 pdf 中图片的宽高
    const imgWidth = 595.28;
    const imgHeight = (592.28 / contentWidth) * contentHeight;
    const img = canvas.toDataURL('image/jpeg', 1.0);
    const pdf = new jspdf.jsPDF('', 'pt', 'a4');
    // 有两个高度需要区分,一个是html页面的实际高度,和生成 pdf 的页面高度(841.89)
    // 当内容未超过 pdf 一页显示的范围,无需分页
    if (leftHeight < pageHeight) {
      pdf.addImage(img, 'JPEG', 0, 0, imgWidth, imgHeight);
    } else {
      while (leftHeight > 0) {
        console.log(imgWidth, imgHeight, position, leftHeight);
        pdf.addImage(img, 'JPEG', 0, position, imgWidth, imgHeight);
        leftHeight -= pageHeight;
        position -= 841.89;
        // 避免添加空白页
        if (leftHeight > 0) {
          pdf.addPage();
        }
      }
    }
    // 6 挂载至页面
    const blob = dataURLtoBlob(pdf.output('datauristring'));
    console.log(blob);
    const url = window.URL.createObjectURL(blob); //获得一个pdf的url对象
    location.href = url;
    // window.open(url, '_blank')//打开一个新窗口
    // console.log(url);
    // URL.revokeObjectURL(url) //释放内存
    // const base64String = btoa(pdf.output());
    // const embed = `<embed type="application/pdf" src="data:application/pdf;base64, ${base64String}" width="100%" height="100%">`;
    // document.documentElement.style.overflow = 'hidden';
    // document.body.innerHTML = embed;
  });
}

dataURLtoBlob 函数如下:

// 当 base64 过大时会导致页面无法加载,需要转化成 blob 格式
function dataURLtoBlob(dataurl: any) {
  const arr = dataurl.split(',');
  // 注意base64的最后面中括号和引号是不转译的
  const _arr = arr[1].substring(0, arr[1].length - 2);
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(_arr);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {
    type: mime,
  });
}
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 19
    评论
可以使用html2canvasjspdf来将前端HTML页面换为PDF格式,同支持CSS3样式。 首先,需要引入html2canvasjspdf的相关库文件。然后,在页面加载完成后,使用html2canvas将HTML页面换为canvas,再使用jspdfcanvas导出PDF格式。 以下是一个简单的示例代码: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML to PDF</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script> </head> <body> <div id="content"> <h1>Hello, World!</h1> <p>This is a sample HTML page.</p> </div> <button onclick="generatePDF()">Generate PDF</button> <script> function generatePDF() { html2canvas(document.getElementById('content'), { onrendered: function(canvas) { var pdf = new jsPDF('p', 'mm', 'a4'); pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298); pdf.save('html2pdf.pdf'); } }); } </script> </body> </html> ``` 在上述示例代码中,我们使用了一个包含`id`为`content`的`div`元素作为待换的HTML页面。我们在页面底部添加了一个按钮,当用户点击按钮调用`generatePDF`函数。 在`generatePDF`函数中,我们使用`html2canvas`将`content`元素换为canvas,然后使用`jspdf`将canvas导出PDF格式并进行下载。 需要注意的是,我们在创建`jspdf`对象指定了页面大小为A4,如果需要生成其他页面大小的PDF文件,可以修改相关参数。另外,`onrendered`回调函数用于在canvas渲染完成后执行相应的操作,这里使用了该函数来导出PDF文件。 综上所述,以上代码可以将前端HTML页面换为PDF格式,并支持CSS3样式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值