vue打印局部内容或组件内容

在页面直接调用window.print(),默认会打印当前document内容,样式/图片还有<body>里面的html标签。

一般我们打印当前页面,不会是整个页面,而只是打印当前页面部分内容而已。

于是我们可以这样:把当前需要打印的组件内容给到iframe的body,样式我们就拿当前document里面的样式。

我们可以创建一个 PrintView.vue :

<template>
  <div class="print">
    <iframe id="iframe" style="display: none;"></iframe>
  </div>
</template>
<script>
export default {
  name: "print",
  props: {},
  watch: {},
  methods: {
    setBodyHtml(html) {
      const document = window.document;
      const iframe = window.frames[0];
      iframe.document.head.innerHTML = document.head.innerHTML; // 获取当前文档的头部给iframe
      iframe.document.body.innerHTML = html; // 把传过来的html给iframe头部

      // 图片和样式加载完成
      Promise.all([this.loadStyle()]).then(res => {
        console.log('打印',res);
        //   打印
        iframe.window.print();
      });
    },
    loadStyle() {
      const iframe = window.frames[0];
      const styles = iframe.document.head.getElementsByTagName("style"); // <style>
      const links = iframe.document.head.getElementsByTagName("link"); // <link>
      let arrs = [];
      arrs = arrs.concat(...styles, ...links);
      console.log(arrs);
      return new Promise((resolve, reject) => {
        for (let i = 0; i < arrs.length; i++) {
          arrs[i].onload = function() {
            if (i === arrs.length - 2) {
              console.log("style 样式加载完成");
              resolve("style 样式加载完成");
            }
          };
        }
      });
    },
    loadImage() {
      const iframe = window.frames[0];
      const imgs = iframe.document.body.getElementsByTagName("img"); // <img>
      return new Promise((resolve, reject) => {
        for (let i = 0; i < imgs.length; i++) {
          console.log('图片');
          imgs[i].onload = function() {
            if (i === imgs.length - 1) {
              console.log("img 加载完成");
              resolve("img 加载完成");
            }
          };
        }
      });
    }
  }
};
</script>

组件中的iframe默认不显示的,因为不需要看到它,打印预览有电脑的打印预览.

 

然后将组件引入需要打印功能的页面,调用 setBodyHtml(html) ,参数为需要打印的文档内容。

this.$refs.PrintView.setBodyHtml(html);

如下图,我只需打印中间的文档内容,innerHTML方法获取文档内容传到iframe里。

点击打印就会弹出浏览器的打印窗口,这样就可以打印需要的组件内容了

这只是粗略的实现了功能,但还是有很多可以优化的地方,有什么不对的或者建议,欢迎各位大佬指出。

 

posted @ 2021-03-23 21:49  小明明同学  阅读(2006)  评论(1)    收藏  举报