Lim Han Yang
Lim Han Yang

Reputation: 440

how to print a specific image through onclick

I need to be able to print out specifically just the image class="main" when I click on the img class="print" within the same div class="imgcontainer", so three separate images individually printed.

HTML

            <div id="printables">
                <div class="imgcontainer">
                    <img class="main" src="assets/printables/Header Ipad.jpg">
                    <img class="print" src="assets/print.png">
                    <a href="assets/printables" download>
                        <img class="download" src="assets/download.png">
                    </a>
                </div>
                <div class="imgcontainer">
                    <img class="main" src="assets/printables/Milestones Chart.jpg">
                    <img class="print" src="assets/print.png">
                    <a href="assets/printables/Milestones Chart.jpg" download>
                        <img class="download" src="assets/download.png">
                    </a>
                </div>
                <div class="imgcontainer">
                    <img class="main" src="assets/printables/FinancialRuler Diagram.jpg">
                    <img class="print" src="assets/print.png">
                    <a href="assets/printables/FinancialRuler Diagram.jpg" download>
                        <img class="download" src="assets/download.png">
                    </a>
                </div>
            </div>

Upvotes: 1

Views: 398

Answers (1)

matthias_h
matthias_h

Reputation: 11416

You can try the following approach to print the images:

 $("img.print").on("click", function() {
    let mainImage = $(this).prev(".main").attr("src"); 
    ImagePrint(mainImage);
 });

 function ImageSourcetoPrint(source) {
    return "<html><head><script>function step1(){\n" +
   "setTimeout('step2()', 10);}\n" +
   "function step2(){window.print();window.close()}\n" +
   "</scri" + "pt></head><body onload='step1()'>\n" +
   "<img src='" + source + "' /></body></html>";
 }

 function ImagePrint(source) {
   Pagelink = "about:blank";
   var pwa = window.open(Pagelink, "_new");
   pwa.document.open();
   pwa.document.write(ImageSourcetoPrint(source));
   pwa.document.close();
 }

This solution is taken from here.

Upvotes: 1

Related Questions