2008-10-23 49 views
54

我有一個應該啓動打印預覽頁面onload的頁面。如何從Javascript調用Print Preview?

我發現這一點:

var OLECMDID = 7; 
/* OLECMDID values: 
* 6 - print 
* 7 - print preview 
* 1 - open window 
* 4 - Save As 
*/ 
var PROMPT = 1; // 2 DONTPROMPTUSER 
var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>'; 
document.body.insertAdjacentHTML('beforeEnd', WebBrowser); 
WebBrowser1.ExecWB(OLECMDID, PROMPT); 
WebBrowser1.outerHTML = ""; 

但是......

  1. 它不工作在Firefox。
  2. 這有點醜。

有沒有更好的IE瀏覽器方式或適用於FireFox的方式?

回答

34

不能,Print Preview是瀏覽器的一個功能,因此應該避免被JavaScript調用,因爲這會帶來安全風險。

這就是您的示例使用Active X的原因,它繞過了JavaScript安全問題。

所以改爲使用您已經擁有的打印樣式表,並將其顯示爲media = screen,print而不是media = print。

閱讀Alist Apart: Going to Print關於打印樣式表主題的好文章。

+5

關於ALA的文章已移動:http://www.alistapart.com/articles/goingtoprint/ – Roman 2009-09-26 16:26:38

18

我認爲跨瀏覽器JavaScript中最好的可能性是window.print(),它在Firefox 3中對我來說,帶來了「打印」對話框而不是打印預覽對話框。

3

它可以使用JavaScript來完成。 說你的HTML/ASPX代碼都這樣說:

<span>Main heading</span> 
<asp:Label ID="lbl1" runat="server" Text="Contents"></asp:Label> 
<asp:Label Text="Contractor Name" ID="lblCont" runat="server"></asp:Label> 
<div id="forPrintPreview"> 
    <asp:Label Text="Company Name" runat="server"></asp:Label> 
    <asp:GridView runat="server"> 

     //GridView Content goes here 

    </asp:GridView 
</div> 

<input type="button" onclick="PrintPreview();" value="Print Preview" /> 

這裏對「打印預覽」按鈕的點擊,我們將打開一個窗口,用於打印數據。 注意'forPrintPreview'是div的id。 的打印預覽功能變爲這樣:

function PrintPreview() { 
var Contractor= $('span[id*="lblCont"]').html(); 
printWindow = window.open("", "", "location=1,status=1,scrollbars=1,width=650,height=600"); 
printWindow.document.write('<html><head>'); 
printWindow.document.write('<style type="text/css">@media print{.no-print, .no-print *{display: none !important;}</style>'); 
printWindow.document.write('</head><body>'); 
printWindow.document.write('<div style="width:100%;text-align:right">'); 

    //Print and cancel button 
printWindow.document.write('<input type="button" id="btnPrint" value="Print" class="no-print" style="width:100px" onclick="window.print()" />'); 
printWindow.document.write('<input type="button" id="btnCancel" value="Cancel" class="no-print" style="width:100px" onclick="window.close()" />'); 

printWindow.document.write('</div>'); 

//You can include any data this way. 
printWindow.document.write('<table><tr><td>Contractor name:'+ Contractor +'</td></tr>you can include any info here</table'); 

printWindow.document.write(document.getElementById('forPrintPreview').innerHTML); 
//here 'forPrintPreview' is the id of the 'div' in current page(aspx). 
printWindow.document.write('</body></html>'); 
printWindow.document.close(); 
printWindow.focus(); 
} 

觀察到按鈕「打印」和「取消」有CSS類「無印」,那麼這些按鈕將不會出現在打印。