简体   繁体   中英

How to print image from browser using JavaScript

I'm able to print the webpage with the image using JavaScript. But it will print out the whole page with white spaces. What can I do to be able to just print out the Image using JavaScript?

Load images on your page with just the necessary resolution you need. In your javascript, pass the highest resolution image url to Print.js for a better print quality.

Import printjs library: printJS('images/print-01-highres.jpg', 'image')

Check this JavaScript library which provide much more options to print from html view.

http://printjs.crabbly.com/

https://www.cssscript.com/javascript-library-printing-elements-page-print-js/

Use window.open to open the image in a separate window, then print that .

Alternately, hide everything except the image (using either JavaScript or @media CSS) before printing.

You can use html2canvas ( https://html2canvas.hertzen.com/ ) to capture the image (s) of your choice from html page and print them. Below is is simple code for capturing image or check fork of one of such example on codepen

<div id="capture" style="padding: 10px; background: #f5da55">
    <h4 style="color: #000; ">Hello world!</h4>
    <img src="https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" />
</div>

html2canvas(document.querySelector("#capture")).then(canvas => {
    document.body.appendChild(canvas)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM