简体   繁体   中英

Print window does not print whole page in chrome latest version

I'm developing a printing tool using HTML5 canvas. By open a new window and write the page canvas as image in new window document then finally print the window document.As a test, I've tried to print the pages(greater than 100 pages) in chrome latest version (Version 46.0.2490.71) it does not print the whole page. In chrome print preview window display only partial page like if we print the 110 pages document means it display only 24 or 38 pages(it display the page randomly). But the whole pages are added in the newly created window for printing. I used the below code for printing the pages.

var _printWindow = window.open('');
_printWindow.document.write('<html><BODY>');
_printWindow.document.write('<center>');
for (var i = 1; i <= _totalPages; i++) {
   var canvas = this._printpages(i);
  _printWindow.document.write('<img src="' + canvas.toDataURL() + '"style="border:1px solid;height:"' + _pageHeight + '"px;margin:0px"><br />');
}
_printWindow.document.write('</center></body></html>');
_printWindow.document.close();
_printWindow.print();

You are calling print() directly after you have finished writing the <img> tags. However, it takes time for all those images to load (asynchronously). Thus, by the time you call print() , the images have not yet finished loading and some may not have had their height determined yet, resulting in an unexpected number of pages.

To fix this, you should call print() only after the onload event has fired on all of the image elements . Here is how I solved it:

var nImages = _totalPages;
function imageLoaded() {
    if (--nImages === 0) {
        _printWindow.print();
    }
}

// ...snip...

// replace your `for` loop with the following:
for (var i = 1; i <= _totalPages; i++) {
    var img = new Image;
    img.addEventListener('load', imageLoaded);
    img.src = /* get the data URL from the canvas */;

    // here, add in your style properties

    _printWindow.document.body.appendChild(img);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM