html2canvas + jsPDF 在IE中多页

html2canvas + jsPDF multiple pages in IE

我必须从 Web 应用程序打印比普通 A4 页面长的网页(所以基本上我需要创建一个 pdf 以在多个 pdf 页面中显示我的所有网页)。 目前我使用的是html2canvas+jsPDF; chrome 他们工作正常。问题是我还需要它们在 IE11 和可能的 IE9 上工作(我已经通过使用 polyfill 解决了“承诺”问题)。

在 IE 上,该功能确实打印文档,但仅打印网页的第一部分(用户无需向下滚动即可看到的内容)。

代码如下:

<script src="${pageContext.request.contextPath}/jsp/shared/silef2/lib/jsPDF/polyfills.es.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/jsp/shared/silef2/lib/jsPDF/jspdf.es.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/jsp/shared/silef2/js/html2canvas.js" type="text/javascript"></script> 


<script>
  function functionPrint()  {

        html2canvas(document.getElementsByTagName("html"),{
            onrendered:function(canvas){

                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;

                doc.addImage(imgData, 'jpeg', 0, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;

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

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

不幸的是,控制台没有返回任何错误信息。我猜想 jsPDF 和 IE 之间存在某种不兼容问题。

我发现 IE11 默认有 属性“溢出:隐藏”,因此,在打印之前,您需要像这样手动覆盖 属性:

<script>
  function functionPrint()  {

        document.getElementById("main").parentNode.style.overflow = 'visible';   <-- THIS

        html2canvas(document.getElementsByTagName("html"),{
            onrendered:function(canvas){

                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;

                doc.addImage(imgData, 'jpeg', 0, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;

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

它仅适用于 getElementById,因此您需要准确识别构成整个页面的元素。