The printing image could be handled inside the button's click
event:
// Query the element
const printBtn = document.getElementById('print');
printBtn.addEventListener('click', function() {
...
});
// Create a fake iframe
const iframe = document.createElement('iframe');
// Make it hidden
iframe.style.height = 0;
iframe.style.visibility = 'hidden';
iframe.style.width = 0;
// Set the iframe's source
iframe.setAttribute('srcdoc', '<html><body></body></html>');
document.body.appendChild(iframe);
Despite the fact that the iframe source is a simple HTML, not a remote path as defined by the src
attribute, we have to wait for the iframe to be loaded completely:
iframe.addEventListener('load', function () {
// Clone the image
const image = document.getElementById('image').cloneNode();
image.style.maxWidth = '100%';
// Append the image to the iframe's body
const body = iframe.contentDocument.body;
body.style.textAlign = 'center';
body.appendChild(image);
});
Invoke the print()
function on the iframe's window as soon as the image is loaded:
iframe.addEventListener('load', function() {
...
image.addEventListener('load', function() {
// Invoke the print when the image is ready
iframe.contentWindow.print();
});
});
Tip
This post uses the Attach event handlers inside other handlers tip
The dynamic iframe will be removed when user starts printing the image or closes the print window:
iframe.contentWindow.addEventListener('afterprint', function () {
iframe.parentNode.removeChild(iframe);
});
Pressing the Print button below to see it in action!