vue实现打印功能

github的跳转连接

下载print.js到本地,放入静态资源文件中,在main.js中引入:

import Print from './util/print'
Vue.use(Print)

在需要打印的页面直接调用就可以了

<template>
    <div ref=print>
        需要打印的内容
    </div>
    <div @click=“print”>点击打印 </div>        
</template>

<script>
   methods:{
    pritn(){
      this.$print(this.$refs.print)
   }
}
</script>

这样就可以是不是很简单

原本看他的文档是可以筛选不打印的元素,但是试了下不行

于是我就把不打印的元素在打印的时候直接隐藏

handlePrint () {
      this.showBtn = false  // 隐藏因素
      setTimeout(() => {
        this.$print(this.$refs.print)
        this.showBtn = true // 显示元素
      }, 50)
    },

这样就OK了
============================= 华丽的分割线 =================================

存在的问题:

上述方法在打印大型文档,会出现打印不全的问题。

解决方法:

window.print() 自带方法解决。先把需要打印的内容,拷贝到一个新的窗口中,然后再用window自带的打印window.print()来实现打印。

html部分

<template>
  <div>
    <div id="printContent">
      ...
    </div>

    <div @click="winPrint()">打印</div>
  </div>
</template>

js部分

winPrint() {
      let curId,timer,timer2,newStr,wind,cssUrl,nodeEnv,new_element;
     
      newStr = document.getElementById(curId).innerHTML;
      wind = window.open(
        "",
        "newwindow",
        "height=660, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no"
      );
      wind.document.body.innerHTML = newStr;
      new_element = document.createElement("link");

      new_element.setAttribute("rel", "stylesheet");
      new_element.setAttribute("style", "text/css");

     //针对开发环境和生产环境分别设置css
      cssUrl = "";
      nodeEnv = process.env.VUE_APP_MODE;
      if (nodeEnv === "development" || nodeEnv === "test") {
        cssUrl = process.env.VUE_APP_MAP_URL + "/css.css";
      } else if (nodeEnv === "production") {
        cssUrl = "https://xxx/css.css";
      }
      new_element.setAttribute(
        "href",
        cssUrl
      );
      
      wind.document.body.appendChild(new_element);
      clearTimeout(timer);
      clearTimeout(timer2);
      timer = setTimeout(() => {
        wind.window.print();
        timer2 = setTimeout(() => {
          wind.window.close();
        }, 0);
      }, 1000);

      return false;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。