JS 前端自适应打印

第一种打印:

首先是安装

1
npm install --save html2canvas

  

然后在 utils 包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import html2canvas from "html2canvas";
 
// 打印类属性、方法定义
/* eslint-disable */
const Print = function (dom, options) {
  if (!(this instanceof Print)) return new Print(dom, options);
 
  this.options = this.extend(
    {
      noPrint: ".no-print",
    },
    options
  );
 
  if (typeof dom === "string") {
    this.cloneDom = document.querySelector(dom);
  } else {
    this.isDOM(dom);
    this.cloneDom = this.isDOM(dom) ? dom : dom.$el;
  }
 
  //主要修改:将打印的dom转换成图片
  html2canvas(this.cloneDom).then((canvas) => {
    this.imgmap = canvas.toDataURL();
    setTimeout(() => {
      this.dom = `<div style='width:100%;height:100%;'><img style='width:100%;height:auto;' src='${this.imgmap}'/></div>`;
      this.init();
    });
  });
};
Print.prototype = {
  init: function () {
    var content = this.dom;
    this.writeIframe(content);
  },
  extend: function (obj, obj2) {
    for (var k in obj2) {
      obj[k] = obj2[k];
    }
    return obj;
  },
 
  writeIframe: function (content) {
    var w,
      doc,
      iframe = document.createElement("iframe"),
      f = document.body.appendChild(iframe);
    iframe.id = "myIframe";
    //iframe.style = "position:absolute;width:0;height:0;top:-10px;left:-10px;";
    iframe.setAttribute(
      "style",
      "position:absolute;width:0;height:0;top:-10px;left:-10px;"
    );
    w = f.contentWindow || f.contentDocument;
    doc = f.contentDocument || f.contentWindow.document;
    doc.open();
    doc.write(content);
    doc.close();
    var _this = this;
    iframe.onload = function () {
      _this.toPrint(w);
      setTimeout(function () {
        document.body.removeChild(iframe);
      }, 100);
    };
  },
 
  toPrint: function (frameWindow) {
    try {
      setTimeout(function () {
        frameWindow.focus();
        try {
          if (!frameWindow.document.execCommand("print", false, null)) {
            frameWindow.print();
          }
        } catch (e) {
          frameWindow.print();
        }
        frameWindow.close();
      }, 10);
    } catch (err) {
      console.log("err", err);
    }
  },
  isDOM:
    typeof HTMLElement === "object"
      ? function (obj) {
          return obj instanceof HTMLElement;
        }
      : function (obj) {
          return (
            obj &&
            typeof obj === "object" &&
            obj.nodeType === 1 &&
            typeof obj.nodeName === "string"
          );
        },
};
const MyPlugin = {};
MyPlugin.install = function (Vue, options) {
  // 4. 添加实例方法
  Vue.prototype.$print = Print;
};
export default MyPlugin;

  

main.ja 挂载

1
2
3
//打印JS文件
import Print from "@/utils/print";
Vue.use(Print); // 注册

  

应用

1
this.$print(document.getElementById(" 这里是要打印的内容的外层 div 的 id "));

  

第二种方法:

在调用打印方法内放置以下内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//获取打印的页面内容
      let subOutputRankPrint = document.getElementById("print1");
      let newContent = subOutputRankPrint.innerHTML;
      let oldContent = document.body.innerHTML;
      document.body.innerHTML = newContent;
      //页面打印缩放比例设置
      document.getElementsByTagName("body")[0].style.zoom = 0.92;
      //检测是否是IE 如果是ie进行页眉页脚
      if (!!window.ActiveXObject || "ActiveXObject" in window) {
        var hkey_root, hkey_path, hkey_key;
        hkey_path =
          "HKEY_CURRENT_USER\\Software\\Microsoft\\Internet" +
          "Explorer\\PageSetup\\";
        try {
          var RegWsh = new ActiveXObject("WScript.Shell");
          RegWsh.RegWrite(hkey_path + "header", "");
          RegWsh.RegWrite(hkey_path + "footer", "");
        } catch (e) {}
      }
      window.print();
      window.location.reload();
      //将原有页面还原到页面
      document.body.innerHTML = oldContent;
      return false;

  

加上 scss

@page {
  /* 纵向打印 */
  size: portrait;

  margin: 5mm;
}

 

1
2
3
4
5
6
7
8
9
10
11
<style lang="scss" scoped>
// chrome下进行页眉页脚消除 使用css 样式进行消除
// 测试ie11,chrome,firefox,edge 可消除页眉页脚
@media print {
  @page {
    margin: 0;
    //控制是使用a4还是使用其它纸张规格
    size: auto;
  }
}
</style>

  

 

posted @   柠檬-不加糖  阅读(618)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2021-12-09 sourcetree 账号密码输入错误解决方案
点击右上角即可分享
微信分享提示