使用html2canvas转换table为图片时合并单元格rowspan失效,无边框显示问题解决(React实现)

最近使用 html2canvas导出Table表单为图片,但是转换出的图片被合并的单元格没有显示边框

查了原因是因为我为tr设置了背景色,然后td设置了rowspan,设置了rowspan的单元格就会出现边框不显示的问题。

解决方法就是取消tr的背景色,然后在td里设置背景色

或者把tr的背景色设置为透明,在td里设置背景色(对于使用了第三方表单的Table组件)-如果用的组件table,tr的背景色也是组件设置的。所以tr样式用这个覆盖background-color: transparent;,再设置单元格的background-color

最后就正常显示了,可以打印了

实现代码:

TypeScript 复制代码
    // 生成图片快照 DOM nodes convert to PNG
    const saveImage = async () => {
        const canvas = await html2canvas(document.getElementById('capture'),{scale:2})
        const link = document?.createElement('a')
        link.download = `标签${data?.wastesName != null ? '-' : ''}${data?.wastesName??''}.png`
        link.href = canvas.toDataURL('image/png')
        link?.click()

    }

    /**
     * 打印及关闭窗口
     * @param printWindow Windows对象
     */
    const openPrint = async (printWindow: any) => {
        await printWindow?.print();
        printWindow?.close()
    }

    /**
     * 打印
     */
    const handlePrint = async () => {
        const canvas = await html2canvas(document.getElementById('capture'),{scale:2})
        const printWindow = window?.open('', '_blank');
        printWindow?.document?.open();
        printWindow?.document?.write('<html lang="zh"><head><title>打印</title></head><body>');
        printWindow?.document?.write('<img src="' + canvas.toDataURL('image/png') + '" style="width:100%" alt="">');
        printWindow?.document?.write('</body></html>');
        printWindow?.document?.close();
        // 在整个HTML文档加载完成后执行的操作
        printWindow.onload = () => openPrint(printWindow)
    };

当然你也可以用另一个库实现,我之前写了另一个库的实现方式,这个库在复制dom元素时会用到浏览器Window对象,但我们这套前端框架是通过微前端构建的,子应用中的Window对象被沙箱隔离了,无法使用Window对象的部分原生方法,所以我才转用html2canvas库的,该库中没用到Window对象,所以可以使用,但方便的还是HTML-to-image,使用链接:JavaScript实现React实现网页转换成图片截屏下载_react截取页面保存为图片到手机相册-CSDN博客

参考文献:

0、Features | html2canvas

1、html2canvas 踩坑记录一_html2canvas导出table rowspan失效-CSDN博客

相关推荐
PineappleCoder7 小时前
还在重复下载资源?HTTP 缓存让二次访问 “零请求”,用户体验翻倍
前端·性能优化
拉不动的猪7 小时前
webpack编译中为什么不建议load替换ast中节点删除consolg.log
前端·javascript·webpack
李姆斯7 小时前
Agent时代下,ToB前端的UI和交互会往哪走?
前端·agent·交互设计
源码获取_wx:Fegn08958 小时前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
闲谈共视8 小时前
基于去中心化社交与AI智能服务的Web钱包商业开发的可行性
前端·人工智能·去中心化·区块链
CreasyChan8 小时前
C# 反射详解
开发语言·前端·windows·unity·c#·游戏开发
JIngJaneIL8 小时前
基于Java+ vue智慧医药系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
阿蒙Amon9 小时前
JavaScript学习笔记:6.表达式和运算符
javascript·笔记·学习
hashiqimiya10 小时前
两个步骤,打包war,tomcat使用war包
java·服务器·前端
小a杰.10 小时前
Flutter 设计系统构建指南
开发语言·javascript·ecmascript