vue打印瀏覽器頁面功能的兩種實現方法


推薦使用方法二

方法一:通過npm 安裝插件

1,安裝 npm install vue-print-nb --save

2,引入 安裝好以後在main.js文件中引入

1
import Print from 'vue-print-nb'

Vue.use(Print); //註冊

3,現在就可以使用了

1
2
3
4
5
div id="printTest" >
      <p>明月照于山間</p>
      <p>清風來於江上 </p>
    </div>
    <button v-print="'#printTest'">打印</button>

4.如需通過鏈接地址打印:window.location.href = airway_bill; airway_bill爲鏈接地址。

5.如果內容打印不全,在打印操作時點擊更多設置,然後設置縮放。

方法一使用時可能會遇到內容只有一頁,但是點擊打印會打印2張的情況。解決辦法:查看定義的元素高度是否有被設置爲100%,或html高度被設置成100%,如果有去掉即可。

方法二:手動下載插件到本地

插件地址:https://github.com/xyl66/vuePlugs_printjs

1.在src下新建文件夾plugs,將下載好的print.js放入plugs文件夾下

2.在main.js中引入

print.js 裏的代碼

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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//print.js 裏的代碼
// 打印類屬性、方法定義
/* 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.dom = document.querySelector(dom);
    } else {
      this.dom = dom;
    }
   
    this.init();
  };
  Print.prototype = {
   
    init: function () {
      var content = this.getStyle() + this.getHtml();
      this.writeIframe(content);
    },
     
    extend: function (obj, obj2) {
      for (var k in obj2) {
        obj[k] = obj2[k];
      }
      return obj;
    },
   
    getStyle: function () {
      var str = "",
        styles = document.querySelectorAll('style,link');
      for (var i = 0; i < styles.length; i++) {
        str += styles[i].outerHTML;
      }
      str += "<style>" + (this.options.noPrint ? this.options.noPrint : '.no-print') + "{display:none;}</style>";
   
      return str;
    },
   
    getHtml: function () {
      var inputs = document.querySelectorAll('input');
      var textareas = document.querySelectorAll('textarea');
      var selects = document.querySelectorAll('select');
   
      for (var k in inputs) {
        if (inputs[k].type == "checkbox" || inputs[k].type == "radio") {
          if (inputs[k].checked == true) {
            inputs[k].setAttribute('checked', "checked")
          } else {
            inputs[k].removeAttribute('checked')
          }
        } else if (inputs[k].type == "text") {
          inputs[k].setAttribute('value', inputs[k].value)
        }
      }
   
      for (var k2 in textareas) {
        if (textareas[k2].type == 'textarea') {
          textareas[k2].innerHTML = textareas[k2].value
        }
      }
   
      for (var k3 in selects) {
        if (selects[k3].type == 'select-one') {
          var child = selects[k3].children;
          for (var i in child) {
            if (child[i].tagName == 'OPTION') {
              if (child[i].selected == true) {
                child[i].setAttribute('selected', "selected")
              } else {
                child[i].removeAttribute('selected')
              }
            }
          }
        }
      }
   
      return this.dom.outerHTML;
    },
   
    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;";
       
      w = f.contentWindow || f.contentDocument;
      doc = f.contentDocument || f.contentWindow.document;
      doc.open();
      doc.write(content);
      doc.close();
      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);
      }
    }
  };
   
  const MyPlugin = {}
  MyPlugin.install = function (Vue, options) {
    Vue.prototype.$print = Print
  }
   
  export default MyPlugin

main.js裏引入

1
2
import Print from './plugs/print'
Vue.use(Print)

使用

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
<template>
    <div>
        <!-- 點擊按鈕打印 -->
        <el-button type="primary" @click="printDemo">點擊打印</el-button>
         
        <!--  <div ref="print">
            <h1>這裏是打印內容</h1>
        </div>-->
        <img class="printsrcclass" ref='print' :src="printsrc"/>
    </div>   
</template>
<script>
 
export default {
    data(){
        return {}
    },
    methods: {
        // 點擊打印
        printDemo(){
            setTimeout(() => {
                this.$print(this.$refs.print)
            }, 100);
        }
    },
    mounted() {
 
    }
}

4.注意事項 需使用ref獲取dom節點,若直接通過id或class獲取則webpack打包部署後打印內容爲空

5.指定不打印區域

方法1. 添加no-print樣式類

不要打印我

方法2. 自定義類名

不要打印我

1
this. print (this . print(this. print(this.refs.print,{‘no-print':‘.do-not-print-me-xxx'}) // 使用

如果圖片出不來 打印出不來 等情況

參考下面代碼

1
2
3
4
5
6
7
8
9
10
11
12
const res2 = await fnApi(orderId);
 let myBlob = new Blob([res2.data], { type: 'image/jpeg'});
        var href = URL.createObjectURL(myBlob); // 創建對象超鏈接
        // 此時拿到圖片地址 href,後面直接使用該地址即可
        let img = new Image();
        img.src = href;
        img.onload = () => {
          this.printsrc = href;
          this.$nextTick(() => {
            this.mypirntFN();
          })
        }

接口別忘了加類型

Ps:

一,可能遇到的問題及解決方案

①圖片佔位置 ---------讓它脫離文檔流( position: absolute; 不要用fixed 這樣內容多的時候只打印第一頁)

②頁面不想展示打印內容 只打印;------- 給它 z-index:-1 (display:none 的話打印內容也沒有)

目前解決不了 跳過打印預覽直接打印功能 

總結

到此這篇關於vue打印瀏覽器頁面功能的兩種實現方法的文章就介紹到這了,更多相關vue打印瀏覽器頁面功能內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支持腳本之家!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章