打印局部div内容,带样式方法总结

2 篇文章 0 订阅
1 篇文章 0 订阅

接下来我要总结的打印局部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'}}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值