使用html2canvas+jspdf 网页端截图功能

601 阅读1分钟

功能

将我们写的DIV转成图片然后下载成pdf文件

安装

yarn add html2canvas jspdf

使用

import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';


const getPdf = (element, fileName)=>{
        const contentWidth = element.clientWidth; // 获得该容器的宽
        const contentHeight = element.offsetHeight; // 获得该容器的高
        const canvas = document.createElement('canvas');
        const scale = 4; // 数值越大则图片越清晰

        canvas.width = contentWidth * scale;
        canvas.height = contentHeight * scale;
        canvas.getContext('2d').scale(scale, scale);

        const opts = {
          scale,
          canvas,
          width: contentWidth * scale,
          height: contentHeight * scale,
          useCORS: true,  // 允许跨域
          allowTaint: true,
        };
        html2Canvas(element, opts).then((canvas) => {
          const pageData = canvas.toDataURL('image/jpeg', 1.0);
           let direction = 'portrait';  // 方向设置,固定写死的话会有白边问题或出现截图不全
          if (canvas.width > canvas.height) {
            direction = 'landscape';
          }
          const PDF = new JsPDF(direction, 'pt', [canvas.width, canvas.height]);
          PDF.addImage(pageData, 'JPEG', 0, 0, canvas.width, canvas.height);
          PDF.save(`${fileName}.pdf`);
        });
        onCancel();
}

ps

觉得有帮助的,动动小手右上角点赞!觉得哪里有问题的在评论区留言!!!一起摸鱼!!!