Print window does not print the whole page in the latest version of Chrome

I am developing a printing tool using an HTML5 canvas. Having opened a new window and write the page canvas as an image in a new document window, then finally print the window document. As a test, I tried to print pages (more than 100 pages) in the latest version of Chrome (version 46.0.2490.71), it does not print the entire page. The chrome print preview window displays only an incomplete page, for example, if we print a document of 110 pages, this means that it only displays 24 or 38 pages (it displays the page randomly). But all pages are added to the newly created print window. I used the code below to print 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();
+4
source share
1 answer

You call print()immediately after you have finished writing tags <img>. However, it takes time to download all of these images (asynchronously). Thus, by the time you call print(), the images have not finished loading, and some may not have determined their height, which led to an unexpected number of pages.

To fix this, you should print()only call after the event has onloadtriggered all the elements of the image. Here's 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);
}
0
source

Source: https://habr.com/ru/post/1619441/


All Articles