You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IE环境下html2canvas+jsPDF生成长网页多页PDF仅显示首屏问题求助

问题根因

你遇到的IE下仅生成首屏内容的问题并非jsPDF兼容性导致,而是html2canvas在IE内核下的渲染逻辑差异引发的:

  • IE下html2canvas默认基于当前浏览器视口的可见范围截取内容,不会自动计算整个页面的完整滚动高度
  • 你当前传入的渲染对象是<html>节点,IE下该节点的高度计算会受滚动条视口限制,无法读取到完整页面高度
  • 如果用户触发打印时页面不在顶部,IE下会从当前滚动位置开始截取,丢失上方/下方未在视口内的内容
修复方案

1. 调整依赖适配IE版本

首先确认依赖版本符合兼容要求:

  • html2canvas使用1.0.0-rc.4及以下版本,更高版本已放弃IE9/IE11支持
  • 替换当前引入的jspdf.es.js为UMD兼容版本,ES模块化语法不被IE9支持,会导致加载失败

2. 修复打印逻辑

完整修改后的代码如下:

<script src="${pageContext.request.contextPath}/jsp/shared/silef2/lib/jsPDF/polyfills.es.js" type="text/javascript"></script>
<!-- 替换为UMD兼容版本jsPDF -->
<script src="${pageContext.request.contextPath}/jsp/shared/silef2/lib/jsPDF/jspdf.umd.min.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/jsp/shared/silef2/js/html2canvas.js" type="text/javascript"></script> 


<script>
function functionPrint()  {
    // 保存当前页面滚动位置
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
    // 临时滚动到页面顶部,避免IE下渲染偏移
    window.scrollTo(0, 0);

    html2canvas(document.body, {
        // 手动指定完整页面的宽高,强制渲染全部内容
        width: document.body.scrollWidth,
        height: document.body.scrollHeight,
        windowWidth: document.body.scrollWidth,
        windowHeight: document.body.scrollHeight,
        useCORS: true, // 页面存在跨域图片时添加,需确保图片服务允许跨域
        onrendered:function(canvas){
            // 恢复页面原滚动位置
            window.scrollTo(scrollLeft, scrollTop);

            var imgData = canvas.toDataURL('image/png');
            var imgWidth = 210;
            var pageHeight = 295;
            var imgHeight = canvas.height * imgWidth / canvas.width;
            var heightLeft = imgHeight;
            window.jsPDF = window.jspdf.jsPDF;
            var doc = new jsPDF('p', 'mm');
            var position = 0;

            // 格式改为PNG,和toDataURL生成的格式对应,避免IE下格式解析错误
            doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
            heightLeft -= pageHeight;

            while (heightLeft >= 0) {
                position = heightLeft - imgHeight;
                doc.addPage();
                doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;
            }
            doc.save( 'file.pdf');
        }
    });
}
</script>

<button onclick="functionPrint();">STAMPA</button>

内容的提问来源于stack exchange,提问作者Martina Sasso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 09:09:03