Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print an image using javascript

I am trying to print an ASP.NET Image using the example here.

When I use the above example for a div, it works, but I can't adapt it to print anything else. How can I get it to print an Image? Do I wrap the Image in a div and change the ".text()" part in the script to something else?

like image 233
notAnonymousAnymore Avatar asked May 06 '26 12:05

notAnonymousAnymore


1 Answers

Because you're passing a wrong parameter to the printing function. Printing something in JavaScript is as easy as calling window.print(); method. To test it, simply use developer tools of your browser and write into its console:

window.print();

Now, when you want to print something specific, you have two ways:

  1. Create a special stylesheet for printing in the same page, which hides other elements and only shows your specified region.
  2. Or, open a new window, copy what you want there, then print it.

Now, what you can do is to write your own function:

function printImage(image)
{
        var printWindow = window.open('', 'Print Window','height=400,width=600');
        printWindow.document.write('<html><head><title>Print Window</title>');
        printWindow.document.write('</head><body ><img src=\'');
        printWindow.document.write(image.src);
        printWindow.document.write('\' /></body></html>');
        printWindow.document.close();
        printWindow.print();
}

var image = document.getElementById('image');
printImage(image);

and you can also see this function in action here.

Just let the browser open popup, and also note that I only pass the src value of the image element to the new window.

like image 80
Saeed Neamati Avatar answered May 09 '26 02:05

Saeed Neamati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!