Javascript print in a new window won't display images

十年热恋 提交于 2020-01-24 18:09:45

问题


I'am struggling with a problem and I was hoping you can help me. I created a function that prints out data from inputs in a page. However, logo I am using on a print page won't be displayed like as if a link to the image is broken. Any thoughts?

Here is the code:

function printReport() {
    win=null;
    var vin = $("input[name='vin']").val();
    var make = $("select[name='make']").val();
    var printData = '<table width="960" border="0" align="center"> <tr> <td colspan="2"><img src="http://localhost/site/images/logo_print.png" width="291" height="109" /></td> </tr> <tr> <td colspan="2"><div class="print-title" align="center">Service report </div></td> </tr> <tr> <td width="196">Vin:</td> <td width="754"><b>'+ vin +'</b></td> </tr> <tr> <td>Make:</td> <td><b>'+ make +'</b></td> </tr> </table>';
    win = window.open();
    self.focus();
    win.document.open();
    win.document.write('<'+'html'+'><'+'head'+'><'+'style'+'>');
    win.document.write("body, td { height: 25px; font-family: 'PT Sans', sans-serif; font-size: 17px; color:#333333;} .logo{ background:url(http://localhost/clubdfrance/images/logo_print.png); background-repeat:no-repeat; display:block; width:291px; height:109px;} .print-title{ display:block; margin-top:10px; font-size: 25px; }");
    win.document.write('<'+'/'+'style'+'><'+'/'+'head'+'><'+'body'+'>');
    win.document.write(printData);
    win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
    win.document.close();
    win.print();
    win.close();

回答1:


Here is the solution for everyone out there who has this problem. Problem is with the browsers. They are designed not to print images like this in order to save printers ink. Walkaround for this problem is using CSS media print and list-style-image.

CSS:

@media all{
   printed-div{
       display:none;
   }
}

@media print{
   printed-div{
       display:block;
   }
   .logo-print{
       width:291px;
       height:109px;
       display: list-item;
       list-style-image: url(../images/logo_print.png);
       list-style-position: inside;
   }
}

HTML

<div class="printed-div"></div>

JAVASCRIPT

function printReport() {
    $(".printed-div").html();
    var vin = $("input[name='vin']").val();
    var make = $("select[name='make']").val();
    var printData = '<table width="960" border="0" align="center"> <tr> <td colspan="2"><div class="logo-print"></div></td> </tr> <tr> <td colspan="2"><div align="center">Report</div></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td width="260">Vin:</td> <td width="700"><b>'+ vin +'</b></td> </tr> <tr> <td>Make:</td> <td><b>'+ make +'</b></td> </tr> </table>';
    $(".printed-div").append(printData);
}


来源:https://stackoverflow.com/questions/18310324/javascript-print-in-a-new-window-wont-display-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!