使用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博客

相关推荐
tommyrunner几秒前
Cursor rule文件测试 一秒了解AI行为规则文件
前端·cursor
北京_宏哥6 分钟前
《手把手教你》系列基础篇(九十三)-java+ selenium自动化测试-框架设计基础-POM设计模式实现-上篇(详解教程)
java·前端·selenium
Nu1110 分钟前
weakMap 和 weakSet 原理
前端·面试
顾林海12 分钟前
深入理解 Dart 函数:从基础到高阶应用
android·前端·flutter
比特鹰16 分钟前
桌面端跨端框架调研
前端·javascript·前端框架
Ratten17 分钟前
【JavaScript】---- JS原生的深拷贝API structuredClone 使用详解与注意事项
前端·javascript
DarisX18 分钟前
JupyterLab前端二开基础上手指南
前端
ZZZzh18 分钟前
前端开发浏览器调试方法
前端
shmily_yy19 分钟前
Ts支持哪些类型和类型运算(上)
前端