Skip to content

Instantly share code, notes, and snippets.

@abcdeepakr
Created October 5, 2022 20:30
Show Gist options
  • Save abcdeepakr/347657954a7147ed50ed38626d35d347 to your computer and use it in GitHub Desktop.
Save abcdeepakr/347657954a7147ed50ed38626d35d347 to your computer and use it in GitHub Desktop.
Print a div, and load all images before printing
function printDiv() {
var a = window.open('', '', 'height=1000, width=800');
a.document.write('<html>');
response.htmlContent.map(html =>{
// add the html to new window
a.document.write(html);
// always start next content from new page
a.document.write(`<div style = "display:block; clear:both; page-break-after:always;"></div>`);
})
a.document.write('</html>');
a.document.close();
var totalImages = $(a.document.body).find('img').length;
var imageCounter = 0;
console.log('Total Images: ' + totalImages);
$(a.document.body).find('img').each(function () {
console.log($(this))
// CHECK TO SEE IF IMAGE IS CURRENTLY LOADED
if ($(this).prop('complete')) {
imageCounter+=1
} else {
// FIRE THE IMAGE COUNTER AND VALIDATE PAGE STATE WHEN IMAGE LOADS
$(this).on('load', function () {
imageCounter++;
console.log('Images Loaded: ' + imageCounter);
if (imageCounter == totalImages) {
a.print();
}
});
}
});
}
printDiv()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment