由于要打印绘制生成的图片,于是选择使用JS去打印,方法及遇到的问题如下:
目前在chrome内核浏览器和IE实验成功,好用
指定部分内容打印
- function doPrint() {
- bdhtml = window.document.body.innerHTML;
- sprnstr = "<!--startprint-->";
- eprnstr = "<!--endprint-->";
- prnhtml = bdhtml.substr(bdhtml.indexOf(sprnstr) + 17);
- prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));
- window.document.body.innerHTML = prnhtml;
- if (getExplorer() == "IE") {
- pagesetup_null();
- }
- window.print();
- }
我的需求是打印图片,所以在我图片的部分
-
- <img id="image_ZKZ" runat="server" src="" />
-
增加了上述用于截断字符串的内容,这样通过
doPrint()
方法就能够截取到指定的图片内容了
这种情况下打印使用chrome是正常打印,并且没有页眉页脚,但是IE则仍然有,于是在 doPrint() 方法中使用了getExplorer() 方法来获取浏览器类型,以及pagesetup_null() 来去掉IE的页眉页脚,两个方法如下:
-
- function getExplorer() {
- var explorer = window.navigator.userAgent;
-
- if (explorer.indexOf("MSIE") >= 0) {
- return "IE";
- }
-
- else if (explorer.indexOf("Firefox") >= 0) {
- return "Firefox";
- }
-
- else if (explorer.indexOf("Chrome") >= 0) {
- return "Chrome";
- }
-
- else if (explorer.indexOf("Opera") >= 0) {
- return "Opera";
- }
-
- else if (explorer.indexOf("Safari") >= 0) {
- return "Safari";
- }
- }
-
- function pagesetup_null() {
- var hkey_root, hkey_path, hkey_key;
- hkey_root = "HKEY_CURRENT_USER";
- hkey_path = "\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
- try {
- var RegWsh = new ActiveXObject("WScript.Shell");
- hkey_key = "header";
- RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "");
- hkey_key = "footer";
- RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "");
- } catch (e) { }
- }
但是这样打印IE的页边距比较宽,所以相对chrome有点被缩放的感觉,但是整体还可以没有很夸张