'html2pdf starts printing halfway down the page

I'm trying out HTML2PDF javascript.

    function createPDF(){
    var element = document.getElementById('printMe');
    var opt = {
        margin:       1,
        filename:     'myfile.pdf',
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { scale: 1 },
        jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
    };

When I use this the pdf converts etc but it appears halfway down the first page. All of the content is encapsulated in a div

<div id="printMe" style="padding: 20px;padding-right:30px;">.....</div>

I've tried setting the height and removing almost all the content but it still seems to be placing it in the middle of the page as the starting point.

Is there some way of forcing the code to start at the top of the page?



Solution 1:[1]

I solved the issue.

The movement in position of the print is affected by the scroll position of the window. So if the button to create the PDF is at the top of the page and you click it places the text at the top of the PDF. If the button is placed in the visible area of the page and you scroll down until it is at the top of the page - the amount you've scrolled is added to the top of the PDF document.

    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera

I used this code snippet to solve the issue. When I go to print I scroll to the top of the document before creating the PDF.

Solution 2:[2]

Add scrollY: 0 to the html2canvas object in the html2pdf options:

var opt = {
    margin:       1,
    filename:     'myfile.pdf',
    image:        { type: 'jpeg', quality: 0.98 },
    html2canvas:  { scale: 1, scrollY: 0 },
    jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 kfunk