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

相关推荐
知识分享小能手2 小时前
Vue3 学习教程,从入门到精通,Axios 在 Vue 3 中的使用指南(37)
前端·javascript·vue.js·学习·typescript·vue·vue3
程序员码歌5 小时前
【零代码AI编程实战】AI灯塔导航-总结篇
android·前端·后端
用户21411832636026 小时前
免费玩转 AI 编程!Claude Code Router + Qwen3-Code 实战教程
前端
小小愿望7 小时前
前端无法获取响应头(如 Content-Disposition)的原因与解决方案
前端·后端
小小愿望7 小时前
项目启功需要添加SKIP_PREFLIGHT_CHECK=true该怎么办?
前端
烛阴7 小时前
精简之道:TypeScript 参数属性 (Parameter Properties) 详解
前端·javascript·typescript
海上彼尚8 小时前
使用 npm-run-all2 简化你的 npm 脚本工作流
前端·npm·node.js
开发者小天8 小时前
为什么 /deep/ 现在不推荐使用?
前端·javascript·node.js
如白驹过隙9 小时前
cloudflare缓存配置
前端·缓存
excel9 小时前
JavaScript 异步编程全解析:Promise、Async/Await 与进阶技巧
前端