简体   繁体   中英

How to print table with image using javascript?

I've fiddle print table but barcode column showing blank. How can i print table with barcode image?

Sample Javascript code like that

function printData()
{
   var divToPrint=document.getElementById("printTable");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
   newWin.print();
   newWin.close();
}

$('button').on('click',function(){
printData();
})

http://jsfiddle.net/0tc9hb7u/12/

First you need to get all images in your new window

var images = newWin.document.getElementsByTagName("img");

Then you should call newWin.print() only when all images are loaded.

var imagesLoaded = 0;
for (var i = 0; i < images.length; i++) {
    var image = images[i];
    var img = new Image(); 

    img.onload = function () {
        imagesLoaded++;
        // Ok, image was loaded, let's check if it was the last image to load
        if (imagesLoaded === images.length) {
            newWin.print();
        }
    }
    var oneSrc = image.getAttribute('src');

    img.src = oneSrc;
};

Try setting "newWin" as newWin name property ; utilizing setTimeout to delay calling .print() until images loaded in newly opened window

function printData() {
    var divToPrint = document.getElementById("printTable");
    newWin = window.open("", "newWin");
    newWin.document.write(divToPrint.outerHTML);
    setTimeout(function () {
        newWin.print();
    }, 1000)
    // newWin.close();
}

$('button').on('click', function () {
    printData();
})

jsfiddle http://jsfiddle.net/0tc9hb7u/4/

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