Ric*_*ema 62 javascript printing
我有一个页面应该启动打印预览页面onload.
我找到了这个:
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 = "";
Run Code Online (Sandbox Code Playgroud)
但...
有没有更好的方式为IE或适用于FireFox的方式?
sva*_*agt 35
你不能,Print Preview是浏览器的一项功能,因此应该保护它不被JavaScript调用,因为它会带来安全风险.
这就是为什么您的示例使用Active X,它绕过了JavaScript安全问题.
因此,请使用您应该拥有的打印样式表并将其显示为media = screen,而不是media = print.
阅读Alist Apart:去打印以获得关于打印样式表主题的好文章.
它可以使用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" />
Run Code Online (Sandbox Code Playgroud)
点击“打印预览”按钮,我们将打开一个包含打印数据的窗口。观察到 '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();
}
Run Code Online (Sandbox Code Playgroud)
观察按钮 'print' 和 'cancel' 具有 css 类 'no-print',因此这些按钮不会出现在打印中。
归档时间: |
|
查看次数: |
143192 次 |
最近记录: |