Explorar o código

修复线上环境打印样式无效的问题

shmily1213 %!s(int64=2) %!d(string=hai) anos
pai
achega
595b0d0c4e
Modificáronse 1 ficheiros con 41 adicións e 13 borrados
  1. 41 13
      src/views/elective/dispatch/master/info/student.vue

+ 41 - 13
src/views/elective/dispatch/master/info/student.vue

@@ -29,6 +29,7 @@
 import MxCondition from '@/components/MxCondition/mx-condition'
 import { classesResult, getRound } from '@/api/webApi/elective/dispatch'
 import { mapGetters } from 'vuex'
+import LinkVue from '../../../../../layout/components/Sidebar/Link.vue'
 export default {
   components: { MxCondition },
   data() {
@@ -107,23 +108,50 @@ export default {
       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;
+    getStyleFromLink(href) {
+      return new Promise((resolve, reject) => {
+        fetch(href).then(res => {
+          if (res.ok) {
+            res.blob().then(blob => {
+              const reader = new FileReader();
+              reader.readAsText(blob, 'utf-8');
+              reader.onload = () => {
+                if (reader.result && reader.result.length > 0) {
+                  const data = reader?.result??'';
+                  resolve(data);
+                }
+              }
+            })
+          } else {
+            console.log('请求失败');
+          }
+        }).catch(err => {
+          console.log(err);
+          resolve('');
+        });
+      });
     },
-    print(content, title = '') {
+    async print(content, title = '') {
       // 搜集打印需要的样式,把当前document的所有style拿过来
-      // 如果有link引入的样式文件,用通用的方式处理一下
       let style = '',
-      styles = document.querySelectorAll('style');
-      for (let i = 0; i < styles.length; i++) {
-        style += styles[i].outerHTML;
+      stylesNodes = document.querySelectorAll('style, link, meta');
+      const linkPromises = [];
+      for (let i = 0; i < stylesNodes.length; i++) {
+        // 经测试,link的样式文件在iframe中不生效,所以提取所有样式文件内容拼接到style中
+        if (stylesNodes[i].nodeName === 'LINK' && stylesNodes[i].rel === 'stylesheet') {
+          linkPromises.push(this.getStyleFromLink(stylesNodes[i].href));
+        } else {
+          style += stylesNodes[i].outerHTML;
+        }
       }
+      let linkStyles = ''
+      await Promise.all(linkPromises).then(styles => {
+        linkStyles = styles.reduce((prev, next) => {
+          return prev + next;
+        }, '<style type="text/css">');
+      });
+      linkStyles += '</style>';
+      style += linkStyles;
       // 额外的样式
       style += `<style>
       @media print {