在打印 html 内容中添加外部样式表引用后,打印预览为空白

Print Preview Is Blank After adding External Stylesheet reference in print html content

本文关键字:打印 空白 引用 外部样式表 html 添加      更新时间:2023-09-26

我想打印页面的DIV内容。我所做的是使用 JS 检索div 的内容并将其传递给我调用 .print() 的新窗口 obj。文本内容和图像以这种方式显示。就在我将这一行添加到检索到的div 内容时

<link href="myprintstyle.css" rel="stylesheet" type="text/css">

打印预览为空白。我也尝试添加其他样式表,结果相同。无论我添加什么样式表引用来打印 html 内容,相同的结果 - 空白预览页面。这是我的JS代码来打印页面内容。

var printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">');
function Popup(htmldata) 
{
    var mywindow = window.open('test', 'eChallanReceipt', 'height=800,width=800,top=20;left=20');
    var str ="<html><head><title>test</title>"; 
    str+= "</head><body>"+ printDivCSS + htmldata+"</body></html>";
     mywindow.document.write(str);
    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10
    mywindow.print();
    mywindow.close();
    return false;
}

请提出一些修复建议。我想设置打印内容的样式。浏览器: 铬

同样的代码在Mozilla中工作。但是在Chrome中,我遇到了这个问题。

我知道

这是一个古老的问题,但对于现在遇到此问题的任何人来说,这是解决方案。

它显示空白页,因为文档尚未完成加载。 因此,要修复它,请在timeout中添加mywindow.print()

var printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">');
function Popup(htmldata) 
{
    var mywindow = window.open('test', 'eChallanReceipt', 'height=800,width=800,top=20;left=20');
    var str ="<html><head><title>test</title>"; 
    str+= "</head><body>"+ printDivCSS + htmldata+"</body></html>";
     mywindow.document.write(str);
    mywindow.document.close(); // necessary for IE >= 10
    $( mywindow.document).ready(function(){
  //set this timeout longer if you have many resources to load
    setTimeout(function(){
       mywindow.focus();
       mywindow.print();
    },1000);
    return false;
}

CSS应该从页面的头部调用,而不是从正文调用。