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

相关推荐
工业甲酰苯胺3 小时前
TypeScript枚举类型应用:前后端状态码映射的最简方案
javascript·typescript·状态模式
brzhang3 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
止观止3 小时前
React虚拟DOM的进化之路
前端·react.js·前端框架·reactjs·react
goms4 小时前
前端项目集成lint-staged
前端·vue·lint-staged
谢尔登4 小时前
【React Natve】NetworkError 和 TouchableOpacity 组件
前端·react.js·前端框架
Lin Hsüeh-ch'in4 小时前
如何彻底禁用 Chrome 自动更新
前端·chrome
augenstern4166 小时前
HTML面试题
前端·html
张可6 小时前
一个KMP/CMP项目的组织结构和集成方式
android·前端·kotlin
G等你下课6 小时前
React 路由懒加载入门:提升首屏性能的第一步
前端·react.js·前端框架
谢尔登7 小时前
【React Native】ScrollView 和 FlatList 组件
javascript·react native·react.js