2017-01-01 38 views
1

因此,讓我們先從代碼:沒有攜帶樣式表JavaScript的打印功能

 var mywindow = window.open('', 'PRINT', 'height=600,width=800'); 


     mywindow.document.write('<html><head><base href="/" /><title>' + document.title + '</title>'); 
     mywindow.document.write('<style type="text/css" media="print" />table { width: 100%; }</style>'); 
     mywindow.document.write('</head><body >'); 
     mywindow.document.write('<h1> Returns for Today </h1>'); 
     mywindow.document.write(document.getElementById(printableArea).innerHTML); 
     mywindow.document.write('</body></html>'); 

     mywindow.document.close(); // necessary for IE >= 10 
     mywindow.focus(); // necessary for IE >= 10*/ 

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

     return true; 

的代碼是相當有這個輸出工作

enter image description here

,然後當我更改CSS到外部樣式表如下:

mywindow.document.write('<style type="text/css" media="print" />table { width: 100%; }</style>');

mywindow.document.write('<link rel="stylesheet" href="assets/css/printstyles.css" type="text/css" />');

我得到了一個空白打印頁:

enter image description here

但如果我評論的線

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

我得到這個:

enter image description here

含義,外部樣式表正在工作。

外部樣式表僅包括

table { width: 100%; } 

任何想法,爲什麼它不工作?任何幫助將非常感激。

+0

參見[保存預元素作爲CSS PDF](http://stackoverflow.com/q/30135765/) – guest271314

+1

添加媒體=」打印「到您的外部樣式表的引用。 – jeff

+0

@jeff,做到了這一點,它的工作雖然沒有風格哈哈 – FewFlyBy

回答

1

我在Chrome中遇到了同樣的問題。我發現的問題是打印預覽不能完全呈現,但頁面仍然打印沒有問題。

我最終什麼事做了這樣的事情:

var mywindow = window.open("", ...); 
mywindow.document.write("..."); 
mywindow.document.close(); 
setTimeout(function() { 
    mywindow.print(); 
    mywindow.close(); 
}, 10); 
+0

完美。這有效100% – FewFlyBy

+0

問題是加載樣式表是異步的,並且在完成之前調用print()。 – Barmar

+0

如果您添加'