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

相关推荐
大模型铲屎官28 分钟前
HTML5 技术深度解读:本地存储与地理定位的最佳实践
前端·html·html5·本地存储·localstorage·地理定位·geolocation api
一 乐1 小时前
基于vue船运物流管理系统设计与实现(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端·船运系统
m0_528723811 小时前
在React中使用redux
前端·javascript·react.js
傻小胖2 小时前
vue3中customRef的用法以及使用场景
前端·javascript·vue.js
谦谦橘子2 小时前
手把手教你实现一个富文本
前端·javascript
Future_yzx2 小时前
Java Web的发展史与SpringMVC入门学习(SpringMVC框架入门案例)
java·前端·学习
star010-2 小时前
【视频+图文详解】HTML基础4-html标签的基本使用
前端·windows·经验分享·网络安全·html·html5
engchina2 小时前
CSS Display属性完全指南
前端·css
engchina2 小时前
详解CSS `clear` 属性及其各个选项
前端·css·css3
yashunan3 小时前
Web_php_unserialize
android·前端·php