使用jspdf将html页面保存为pdf,如果浏览器缩放,保存的pdf页面内容不完整,为什么?

Using jspdf to save html page as pdf, saved pdf contains incomplete page content if browser is zoomed, Why?

我正在使用 jspdf 和 html2canvas 组合将 html 页面保存为 pdf。单击按钮时,将保存当前页面的 pdf 副本。问题是,如果您放大页面,然后单击按钮,保存的 pdf 包含当前页面的不完整部分。由于缩放,大部分在页面上不可见的部分在保存的 pdf 页面中被截断。解决办法是什么? 下面是点击保存按钮时调用的js代码-

var pdf = new jsPDF('l', 'pt', 'a4');
var source = $('#someId')[0];
var options = {
   background  : '#eee'
};

pdf.addHTML(source, options, function(){
pdf.save('abcd.pdf');
});

编辑

借鉴 Saurabh 的方法,我尝试了非常相似的事情,但没有为任何额外的 div 元素编写代码。在保存为 pdf 之前,我将屏幕尺寸设置为固定宽度,打印后我将宽度恢复为默认正常。它工作正常,如果它失败了,我们也总是可以修复屏幕的高度,这样尽管缩放它在生成的 pdf 中看起来很好。以下是我使用的代码:-

var pdf = new jsPDF('l', 'pt', 'a4');
var source = $('#someId')[0];
var options = {
   background  : '#eee'
};
var width = source.clientWidth;
source.style.width = '1700px';
pdf.addHTML(source, options,                 
function(){
pdf.save('abcd.pdf');
source.style.width = width+'px';
});

我遇到了同样的问题, 为此,我所做的是打印一份副本 div,然后在单击打印按钮时,我使用 margin-top 将 div 副本附加到我的 dom: 500px

得到它的图像后,我隐藏了 div 的副本,并设置 margin-top:0px

我希望这对你有用。

以下是我如何在使用 jsPDF 的新 .html() 方法放大页面时设法获取整页 pdf。首先,我 force the page zoom level back to 100% before converting it to pdf. It's important to reset the scale in html2canvas option 之后,否则它会 returns 一个空白页。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" 
    integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
    crossorigin="anonymous"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<!-- html2canvas 1.0.0-alpha.11 or higher version is needed -->
<script>
    function download() {
        // Bring the page zoom level back to 100%
        const scale = window.innerWidth / window.outerWidth;
        if (scale != 1) {
           document.body.style.zoom = scale;            
        }

        let pdf = new jsPDF('p', 'pt', 'a4');
        pdf.html(document.getElementById('idName'), {
            html2canvas: {
                scale: 1 // default is window.devicePixelRatio
            },
            callback: function () {
                // pdf.save('test.pdf');
                window.open(pdf.output('bloburl')); // to debug
            }
        });
    }
</script>

Update: A better way is to adjust the html2canvas.scale according to the scale factor.

function download() {
    let pWidth = pdf.internal.pageSize.width; // 595.28 is the width of a4
    let srcWidth = document.getElementById('idName').scrollWidth;
    let margin = 18; // narrow margin - 1.27 cm (36);
    let scale = (pWidth - margin * 2) / srcWidth;
    let pdf = new jsPDF('p', 'pt', 'a4');
    pdf.html(document.getElementById('idName'), {
        x: margin,
        y: margin,
        html2canvas: {
            scale: scale,
        },
        callback: function () {
            window.open(pdf.output('bloburl'));
        }
    });
}