打印局部div內容,帶樣式方法總結

接下來我要總結的打印局部div並且帶樣式方法有兩種,分別都是在react項目中使用:

第一種就是簡單粗暴的方式:

1、首先在項目中引入Print.js文件:

/*
 * @Author: 張前領
 * @Date: 2019-10-14 11:04:37
 */

   export default function Print (dom, options) {
    if (!(this instanceof Print)) return new Print(dom, options);

    this.options = this.extend({
      noPrint: '.no-print',
      onStart: function () { },
      onEnd: function () { }
    }, 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, function () {
        document.body.removeChild(iframe)
      });
    },

    toPrint: function (w, cb) {
      var _this = this;
      w.onload = function () {
        try {
          setTimeout(function () {
            w.focus();
            typeof _this.options.onStart === 'function' && _this.options.onStart();
            if (!w.document.execCommand('print', false, null)) {
              w.print();
            }
            typeof _this.options.onEnd === 'function' && _this.options.onEnd();
            w.close();
            cb && cb()
          });
        } catch (err) {
          console.log('err', err);
        }
      }
    }
  };
  window.Print = Print;

在需要打印的地方執行該函數:

例如:

import Print from './Print.js'

function handlePrint() {
  Print("#billDetail");
}

其中Print()函數內部傳遞的參數爲需要打印的div標籤的div,這樣就可以實現了。

 

第二種打印方式是通過自己封裝獲取打印樣式,然後調用此函數即可:

//引入樣式
 function getStyle() {
  var str = "",
    styles = document.querySelectorAll('style,link');
  for (var i = 0; i < styles.length; i++) {
    str += styles[i].outerHTML;
  }
  return str;
}
//調用打印
print=()=>{
  const el = document.getElementById('printRef');
  const iframe = document.createElement('iframe');
  let doc = null;
  iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px;background:blue');
  document.body.appendChild(iframe);
  doc = iframe.contentWindow.document;
  // 引入打印的專有CSS樣式
  doc.write("<html><head>");
  doc.write(`<link rel='stylesheet' href='../index.less' />`);
  doc.write("</head><body>");
  doc.write(el.innerHTML);
  doc.write("</body></html>"); 
  console.log(iframe.contentWindow.document);
  var appendStyle=document.createElement("style");
  appendStyle.innerText=getStyle();
  doc.getElementsByTagName("head")[0].appendChild(appendStyle);
  doc.close();
  // 獲取iframe的焦點,從iframe開始打印
  iframe.contentWindow.focus();
  iframe.contentWindow.print();
  if (navigator.userAgent.indexOf("MSIE") > 0)
  {
      document.body.removeChild(iframe);
  }
}

點擊打印按鈕就會觸發此函數,這樣打印樣式和打印內容都會在打印預覽中展現出來。

記得有一個比較坑的地方,在寫樣式的時候,一定加上如下內容:

@page {
  size: A4;
  margin:20px auto;
}
@media print {
  html, body {
      min-width: 0;
      width: 210mm; 
      height: auto;
      text-align: center!important;
  }
  .print-hide {
      visibility: hidden!important;
      display: none!important;
  }
}

如果還有需求,需要在特定地方換頁,剩餘內容不管本頁有沒有地方都打印在下一頁,此時,需要在換頁地方加上一個樣式

style={{page-break-before:'always'}}

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