使用css打印div内容

rup*_*r18 16 javascript css asp.net

我正在研究一个项目,我想打印div内容.我正在使用的代码满足了我的要求,但我得到了简单的输出而没有应用Css,也没有得到图像.请帮助我.我附上我想要的代码和输出和输出.

码:

function PrintElem(elem) {
    Popup($(elem).html());
}

function Popup(data) {
    var mywindow = window.open('', 'new div', 'height=400,width=600');
    mywindow.document.write('<html><head><title></title>');
    mywindow.document.write('<link rel="stylesheet" href="css/midday_receipt.css" type="text/css" />');
    mywindow.document.write('</head><body >');
    mywindow.document.write(data);
    mywindow.document.write('</body></html>');

    mywindow.print();
    mywindow.close();

    return true;
}
Run Code Online (Sandbox Code Playgroud)

我在点击打印按钮之前得到的输出: 在此输入图像描述

单击打印按钮我得到的输出: 在此输入图像描述

Gir*_*hel 10

您需要将css属性更改mediaprint.在您的函数createPopup()中添加新行,如下所示:

mywindow.document.write( "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" media=\"print\"/>" );
Run Code Online (Sandbox Code Playgroud)


小智 9

如果你想渲染CSS,你必须在打印之前添加一个超时,因为CSS需要一些时间才能应用于HTML,然后你就可以打印它了.

试试这个:

function Popup(data) {
      var mywindow = window.open('', 'new div', 'height=400,width=600');
      mywindow.document.write('<html><head><title></title>');
      mywindow.document.write('<link rel="stylesheet" href="css/midday_receipt.css" type="text/css" />');
      mywindow.document.write('</head><body >');
      mywindow.document.write(data);
      mywindow.document.write('</body></html>');
      mywindow.document.close();
      mywindow.focus();
      setTimeout(function(){mywindow.print();},1000);
      mywindow.close();

      return true;
}
Run Code Online (Sandbox Code Playgroud)

  • 新窗口会立即关闭。用以下方法修复它。setTimeout(function(){ mywindow.print(); mywindow.close(); },1000); (3认同)
  • 谢谢你.我几乎疯了,直到我添加了超时. (2认同)

jam*_*son 5

我的建议是在<body>标签中添加一些 javascript 来进行打印和关闭。

<body onload="window.print();window.close()">

这样做将始终允许有足够的时间在打印窗口打开之前加载文档和 CSS,然后在打印对话框关闭后立即关闭窗口。


Gab*_*ato 0

渲染问题的一个可能原因可能是由于您使用的 CSS 文件和图像的相对路径所致。首先,尝试使用绝对路径。呈现 HTML 结构的事实排除了生成新 HTML 文档的问题。另外,添加media="print"link元素。

这段代码有效,但部分有效:

    (function() {

function createPopup( data ) {
    var mywindow = window.open( "", "new div", "height=400,width=600" );
    mywindow.document.write( "<html><head><title></title>" );
    mywindow.document.write( "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\"/>" );
    mywindow.document.write( "</head><body >" );
    mywindow.document.write( data );
    mywindow.document.write( "</body></html>" );

    mywindow.print();
    //mywindow.close();

    return true;

}
document.addEventListener( "DOMContentLoaded", function() {
    document.getElementById( "print" ).addEventListener( "click", function() {
        createPopup( document.getElementById( "content" ).innerHTML );

    }, false );

});

   })();
Run Code Online (Sandbox Code Playgroud)

我已经删除了 .close() 调用。请记住,某些 CSS 样式可能不适用于打印。