You can print a web page by clicking the Print menu of browser or pressing the shortcut Ctrl+P
(or command+P
on macOS). Calling the window.print()
function provides the same result which prints the entire page.
In order to print an image, we can insert the image element to a fake iframe
element, and call the print()
function on the iframe's window. Assume that the page has an image element and a print button as below:
<img id="image" src="/path/to/image.jpg" /> <button id="print">Print</button>
The printing image could be handled inside the button's click
event:
const printBtn = document.getElementById('print');
printBtn.addEventListener('click', function() {
...
});
Create a fake iframe
const iframe = document.createElement('iframe');
iframe.style.height = 0;
iframe.style.visibility = 'hidden';
iframe.style.width = 0;
iframe.setAttribute('srcdoc', '<html><body></body></html>');
document.body.appendChild(iframe);
Insert the image when the iframe is ready
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 () {
const image = document.getElementById('image').cloneNode();
image.style.maxWidth = '100%';
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() {
iframe.contentWindow.print();
});
});
Remove the iframe
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!
Demo
See also