前端截屏导出pdf格式

需要引入的文件:

import domtoimage from 'dom-to-image';
import pdfMake from 'pdfmake';

需要截取的元素:

<div  ref={screenRef}></div>

点击截取导出:

      <button onClick={captureScreen}>截屏并保存为PDF</button>

  const screenRef = useRef(null);
 const captureScreen = async () => {
  const element = screenRef.current; // 要截取的元素

  const totalHeight = element.scrollHeight; // 页面总高度
  const chunkHeight = 500; // 每个分段的高度

  const numChunks = Math.ceil(totalHeight / chunkHeight); // 计算总段落数
  const chunks = []; // 存储每个段落的图像数据URL

  // 分段截取页面
  for (let i = 0; i < numChunks; i++) {
    const top = i * chunkHeight; // 当前段落的顶部位置
    const bottom = Math.min((i + 1) * chunkHeight, totalHeight); // 当前段落的底部位置

    try {
      // 使用dom-to-image库截取当前段落的元素,并指定高度、宽度和位置进行适当的裁剪
      const dataUrl = await domtoimage.toPng(element, { 
        height: bottom - top,
        width: element.clientWidth,
        style: { transform: `translate(0px, -${top}px)` },
      });

      chunks.push(dataUrl); // 将截取的图像数据URL存储到chunks数组中
    } catch (error) {
      console.error('截图出错:', error);
    }
  }

  const content = chunks.map((dataUrl) => ({ image: dataUrl, width: 500 })); // 将图像数据URL转换为pdfMake可接受的内容格式

  const pdf = new pdfMake.createPdf({ content }); // 创建PDF实例,传入内容参数
  pdf.download('exported_pdf.pdf'); // 下载生成的PDF文件
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值