9
votes

I use Html2Canvas and then jsPdf to export the image.

This is the function:

function exportPdf() {
    content = $("#print");

    var useWidth = content.prop('scrollWidth');
    var useHeight = content.prop('scrollHeight');

    debugger;

    html2canvas((content), { width: useWidth, height: useHeight}).then(function (canvas) {
        debugger;
        var img = canvas.toDataURL("image/png");
        var doc = new jsPDF({
            unit:'px', 
            format:'a4'
        });

        debugger;
        doc.addImage(img, 'JPEG', 0, 0);
        doc.save('test.pdf');
    });
}

I think is taking in consideration the viewport, is like doing a printscreen, of course whatever is below the scroll it doesn't take it into consideration.

Any ideas?

5

5 Answers

20
votes

Call

    window.scrollTo(0,0)

Before calling html2canvas, its seems its a bug but the window needs to be at the top for html2canvas to capture the entire DOM passed to it

7
votes

It happens when window is scrolled. To work around this problem you can pass negative of whatever window is scrolled by.

html2canvas(htmlSource, {scrollY: -window.scrollY}).then(function(canvas) {

// Do Something here

});
1
votes

One of the reason is already mentioned above that is window might be scrolled, so always add this line before u capture image using html2canvas

    window.scrollTo(0,0)

Another problem can be the resolution of image is more than a pdf page, for that you need to get the width and height of PDF document.

var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();

Use it for your image to fit the PDF document.

doc.addImage(imgData, 'JPEG', 0, 0, width, height);

If you want a dynamic sized image not to be distorted and keep the image width/height ratio

 var width = doc.internal.pageSize.getWidth();
 var height = doc.internal.pageSize.getHeight();

 let widthRatio = width / canvas.width;
 let heightRatio = height / canvas.height;

 let ratio = widthRatio > heightRatio ? heightRatio : widthRatio

Followed by

 doc.addImage(imgData, "PNG", 0, 0, canvas.width * ratio, canvas.height * ratio,);
1
votes

Setting windowHeight and height worked for me:

Try like this:

html2canvas(htmlSource,
 {
     height: window.outerHeight + window.innerHeight,
     windowHeight: window.outerHeight + window.innerHeight
     scrollY: -window.scrollY
 }).then(function(canvas) {
    // Do Something here    
});
0
votes

The only thing that worked for me, was to add the following code into my css.

This style code is used to prevent html2canvas limit the rendering to the viewable area.

.html2canvas-container { 
    width: 3000px; 
    height: 3000px; 
}