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

前端 未结 2 644
失恋的感觉
失恋的感觉 2020-12-06 20:53

I am using jspdf and html2canvas combination to save html page as pdf. A pdf copy of current page is saved the moment you click a button. The problem is, if you zoom in the

2条回答
  •  广开言路
    2020-12-06 20:57

    Here is how I managed to get the full page pdf while the page is zoomed in using jsPDF's new .html() method. First, I force the page zoom level back to 100% before converting it to pdf. It's important to reset the scale in html2canvas option after that, otherwise it'll returns a blank page.

    
    
    
    
    

    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'));
            }
        });
    }
    

提交回复
热议问题