如何打印预览从Javascript调用?

我有一个应该启动“打印预览”页面的页面。

我find了这个:

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的工作方式?

您不能,Print Preview是浏览器的一个function,因此应该保护它免受JavaScript的调用,因为这会带来安全风险。

这就是为什么你的例子使用了Active X,它绕过了JavaScript的安全问题。

因此,请使用您已经拥有的打印样式表,并将其显示为media = screen,print而不是media = print。

请阅读Alist Apart:打印有关打印样式表主题的好文章。

我认为跨浏览器JavaScript中最好的可能是window.print() ,它在Firefox 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" /> 

在这里点击“打印预览”button,我们将打开一个带有打印数据的窗口。 注意到'forPrintPreview'是div的id。 打印预览的function是这样的:

 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(); } 

观察button“打印”和“取消”的CSS类“不打印”,所以这些button不会出现在打印。