前端html2canvas打印 HTML页面局部打印

一、功能

前端html2canvas打印 HTML页面局部打印

二、代码

import html2canvas from 'html2canvas';
/**
   * 打印
   */
  const handleDownload = async () => {
    const canvas = await html2canvas(inputRef.current, {
      scale: 1, // 提高分辨率--缩放
      logging: true, // 开启日志
      useCORS: true, // 允许跨域图片
      allowTaint: true, // 允许污染画布
      backgroundColor: '#ffffff', // 背景色
    });
    const dataURL = canvas.toDataURL('image/png');
    // 创建一个新窗口用于打印
    const printWindow = window.open('', '_blank');

    // 将canvas添加到新窗口
    printWindow.document.write('<html><head><title>打印</title></head><body>');
    printWindow.document.write('<img src="' + canvas.toDataURL('image/png') + '"/>');
    printWindow.document.write('</body></html>');

    // 关闭文档写入
    printWindow.document.close();

    // 等待图片加载完成后打印
    printWindow.onload = function () {
      printWindow.print();
      // 可选:打印后关闭窗口
      printWindow.close();
    };
  };

三、容易出现的问题场景

当使用 html2canvas 打印页面时遇到滚动条和内容打印不全的问题

注意:(临时修改后的样式要刚好在屏幕可视区域
因为html2canvas默认只会截取当前可视区域的内容
如果超出部分请再结合方法二使用方法

解决

方法1
打印时 临时修改样式,打印后恢复原来样式
创建打印状态 handleDownloadType:Boolean

 //打印 状态
  const [handleDownloadType, setAssignPersonType] = useState(false);
useEffect(() => {
    if (handleDownloadType) {
    //true是打印页面
      handleDownload();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [handleDownloadType]);
 // 等待图片加载完成后打印
    printWindow.onload = function () {
      printWindow.print();
      // 可选:打印后关闭窗口
      printWindow.close();
      //打印后状态false
      setAssignPersonType(false)
    };
//handleDownloadType 使用
        <div
          className="form"
          style={{
            height: handleDownloadType ? '100%' : 'calc(100% - 64px)',
            overflow: handleDownloadType ? 'hidden' : 'auto',
          }}
        >
//
</div>

方法2
打印时 临时修改样式,打印后恢复原来样式,但是,页面太大超出了屏幕可视区域,还是打印不全:
使用 scrollX 和 scrollY 选项
html2canvas 提供了一些选项来控制截取行为,包括 scrollX 和 scrollY。这些选项可以用于截取页面上的所有内容,而不仅仅是当前可视区域。
核心

      scrollX: 0, // 水平滚动位置
      scrollY: 0, // 垂直滚动位置
      width: inputRef.current.scrollWidth, // 截取的宽度
      height: inputRef.current.scrollHeight, // 截取的高度

完全

 const canvas = await html2canvas(inputRef.current, {
      scrollX: 0, // 水平滚动位置
      scrollY: 0, // 垂直滚动位置
      width: inputRef.current.scrollWidth, // 截取的宽度
      height: inputRef.current.scrollHeight, // 截取的高度
      useCORS: true, // 启用跨域资源支持
      allowTaint: true, // 允许污染图像(如果需要)
      scale: 1, // 缩放比例
      logging: true, // 开启日志输出以帮助调试
      backgroundColor: ' #fff', // 背景颜色(如果需要透明背景)
    });

打印出现 空白页状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值