头疼了几天的网页自动打印,在查看了N多资料后终于实现了,直接上代码:

Code
1
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PrintPage.aspx.cs" Inherits="Demo.Web.PrintPage" %>
2
3
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
<html xmlns="http://www.w3.org/1999/xhtml">
5
<head id="Head1" runat="server">
6
<title>打印单</title>
7
<link href="../CSS/css-main.css" type="text/css" rel="stylesheet" media="all" />
8
<script type="text/javascript">
9
//注册表的网页打印路径
10
var hkey_root="HKEY_CURRENT_USER" ;
11
var hkey_path="\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
12
var hkey_key;
13
14
//打印指定区域
15
function DoPrint()
16
{
17
//直接调用WebBrowser的打印,要打印预览的话是ExecWB(7,1)
18
document.all.WebBrowser.ExecWB(6,1);
19
}
20
21
//设置纸张方向
22
function SetupLandscape()
23

{
24
try
{
25
var wsShell= new ActiveXObject("WScript.Shell");
26
//打印页面的Menubar必须可见,此操作类似按键盘上的Alt+F+U也就是 调出页面设置对话框
27
wsShell.sendKeys(\'%fu\');
28
//此操作类似按键盘上的Alt+A也就是 设置横向打印
29
wsShell.sendKeys(\'%a\');
30
//此操作类似按键盘上的回车 页面设置对话框的默认焦点在 确定上 所以直接确定
31
wsShell.sendKeys(\'{ENTER}\');
32
}
33
catch(e)
{}
34
}
35
36
//设置默认的页眉页脚
37
function SetupPage()
38

{
39
try
{
40
var RegWsh = new ActiveXObject("WScript.Shell");
41
hkey_key="header"
42
RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"&w&b页码,&p/&P")
43
hkey_key="footer"
44
RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"&b&d") //去掉了&u 因为我不想显示当前打印页的网址
45
hkey_key="margin_bottom";
46
RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"0.39"); //0.39相当于把页面设置里面的边距设置为10
47
hkey_key="margin_left";
48
RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"0.39");
49
hkey_key="margin_right";
50
RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"0.39");
51
hkey_key="margin_top";
52
RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"0.39");
53
}
54
catch(e)
{}
55
}
56
57
setTimeout("SetupLandscape()",1000);
58
setTimeout("SetupPage()",2000);
59
setTimeout("DoPrint()",3000);
60
</script>
61
62
</head>
63
<body>
64
<form id="form1" runat="server" enctype="multipart/form-data">
65
<OBJECT id="WebBrowser" height="0" width="0" classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" VIEWASTEXT ></OBJECT >
66
<table width="100%">
67
<tr><td>要打印的内容</td></tr>
68
</table>
69
</form>
70
</body>
71
</html>
72