/html-dom /Intermediate
GitHub 5008★

Print an image

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:

// Query the element
const printBtn = document.getElementById('print');

printBtn.addEventListener('click', function() {

Create a fake iframe

// 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>');


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 () {
// 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';

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


This post uses the Attach event handlers inside other handlers tip

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 () {

Pressing the Print button below to see it in action!

Photo by Rod Long on Unsplash



See also

Follow me on and to get more useful contents.