Jelajahi Sumber

添加打印表格方法

shmily1213 2 tahun lalu
induk
melakukan
c5c0aa818b
1 mengubah file dengan 51 tambahan dan 2 penghapusan
  1. 51 2
      src/views/elective/dispatch/master/info/student.vue

+ 51 - 2
src/views/elective/dispatch/master/info/student.vue

@@ -8,14 +8,14 @@
     <!--   班主任查看  -->
     <el-card class="box-card"  v-if="queryParams.roundId">
       <div slot="header" class="clearfix">
-        <p class="f20 text-center">{{ title }}  <el-button style="float: right;" type="primary">打印</el-button></p>
+        <p class="f20 text-center">{{ title }}  <el-button style="float: right;" type="primary" @click="handlePrint">打印</el-button></p>
       </div>
       <div>
         <div class="mb10 f14 fx-row jc-between">
           <p>备注:<span class="f-red">请通知学生按照学校规定到新班级报道</span></p>
           <span>共{{formatRows.length}}人</span>
         </div>
-        <mx-table :prop-defines="propDefines" :rows="formatRows">
+        <mx-table ref="table" :prop-defines="propDefines" :rows="formatRows">
           <template #tmp="{row}">
             <el-button type="primary">通知</el-button>
           </template>
@@ -106,6 +106,55 @@ export default {
     handleInvalidQuery() {
       console.log('query取消')
       this.round = {}
+    },
+    getStyle () {
+      let str = '',
+      styles = document.querySelectorAll('style');
+      for (var i = 0; i < styles.length; i++) {
+        str += styles[i].outerHTML;
+      }
+      console.log(str)
+      return str;
+    },
+    print(content, title = '') {
+      // 搜集打印需要的样式,把当前document的所有style拿过来
+      // 如果有link引入的样式文件,用通用的方式处理一下
+      let style = '',
+      styles = document.querySelectorAll('style');
+      for (let i = 0; i < styles.length; i++) {
+        style += styles[i].outerHTML;
+      }
+      // 额外的样式
+      style += `<style>
+      @media print {
+        @page {
+            size: A4 landscape;
+        }
+      }
+      </style>`
+      const iframe = document.createElement('iframe');
+      iframe.setAttribute('style', `position: absolute;top: 0;left: 0;width: 11.7in;height: 300px;z-index: -1;opacity: 0;border: none;background-color: #efefef;`)
+      document.body.appendChild(iframe);
+      const doc = iframe.contentDocument;
+      doc.write(style + content);
+      if (title) {
+        doc.title = title;
+      }
+      // 以下设置只对el-table有效,如果打印的不是el-table请注释
+      const thead = doc.querySelector('.el-table__header-wrapper thead');
+      thead.classList.add('el-table__header-wrapper');
+      thead.style.width='100%';
+      const tbody = doc.querySelector('.el-table__body-wrapper table');
+      tbody.appendChild(thead);
+      tbody.style.width='100%';
+      // 打印并移除iframe
+      iframe.contentWindow.print();
+      document.body.removeChild(iframe);
+      // 最后,听说printjs可以直接打印json数据
+    },
+    handlePrint() {
+      // 要打印的节点,页面标题
+      this.print(this.$refs.table.$el.outerHTML, '长沙市103中2021学年第1次选科分班信息');
     }
   }
 }