Cross browser print image javascript

Home/Javascript/Cross browser print image javascript

Hiding sections of a page when printing is a fairly common and trivial task with the help of a little css. For example, hiding a page header and footer only takes a few lines.

@media print {
    .header, .footer {
        display: none;
    }
}

But what if you want to only print a single element, such as an image? You could take the above approach to hide all other elements and only allow the image to be displayed. An alternative approach is to use a little javascript to open the image in a new window and immediately trigger the window.print() method.

$('#print-btn').click(function () {
    printImage('/path/to/image.png');
    return true;
});

function printImage(imagePath) {
    var width = $(window).width() * 0.9;
    var height = $(window).height() * 0.9;
    var content = '<!DOCTYPE html>' + 
                  '<html>' +
                  '<head><title></title></head>' +
                  '<body onload="window.focus(); window.print(); window.close();">' + 
                  '<img src="' + imagePath + '" style="width: 100%;" />' +
                  '</body>' +
                  '</html>';
    var options = "toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,width=" + width + ",height=" + height;
    var printWindow = window.open('', 'print', options);
    printWindow.document.open();
    printWindow.document.write(content);
    printWindow.document.close();
    printWindow.focus();
}

The above script opens a new (nearly fullscreen) window containing the image we want to print. Notice that the body tag has an onload attribute that set’s the window’s focus (needed to make IE happy), calls print, and immediately closes. This tells the window to close after the user exits the print dialog. Note that you could actually move the print() and close() calls to the parent window’s script, printWindow.print() and printWindow().close(). But I found that doing so caused Chrome to display the print window before the image had a chance to load, resulting in an empty page. The version seemed to pacify both Chrome and Internet Explorer.

Tags: |

About the Author:

Freelance software developer in the Cleveland area.

One Comment

  1. romrom May 17, 2016 at 10:32 am - Reply

    Thanks !

Leave A Comment