JS局部打印 Iframe版

首先声明代码魔改自JavaScript类库的jquery.PrintArea.js,官网 https://plugins.jquery.com/PrintArea/ 很好用的插件,但是目前2.4.0版本貌似并没有支持npm安装,而自家公司目前前台用的是VUE + Element,直接引用js并不好使,所有只好自己魔改了一版,毕竟技术不够,复制来凑。目前测试 火狐 IE11  谷歌打印都支持有需要的小伙伴可以领回家试试。

话不多说贴代码

import $ from "jquery";//我目前用的1.8.3版本的JQ
/*********  
 * 局部打印 --iframe版 (依赖jQuery)
 * 使用参考用例
 * import myPrint from 'XXXXXX/myPrint'; 
 * myPrint.doPrint("#id");
 * 目前不支持多块区域拼接打印  原插件支持哦
 * 有多块区域拼接打印需求可扩展getBody()方法即可
 */
class MyPrint { 
    constructor() {
    } 
    modes = { iframe : "iframe", popup : "popup" };
    standards = { strict : "strict", loose : "loose", html5 : "html5" };
    settings = {
      mode       : this.modes.iframe,
      standard   : this.standards.html5,
      popHt      : 500,
      popWd      : 400,
      popX       : 200,
      popY       : 200,
      popTitle   : '',
      popClose   : false,
      extraCss   : '',
      extraHead  : '',
      retainAttr : ["id","class","style"] ,
      id         : new Date().getTime()
    }; 
    doPrint(el) { 
        let iframe = this.createIframe()
        var win = iframe.contentWindow;
        //var $printSource = $('#print-tab');
        var $printSource = $(el);
        this.write( iframe.doc, $printSource ); 
        $(iframe.doc).ready(function(){
          setTimeout( function () { //延时一秒用于背景图片加载
            win.focus();
            win.print();
          }, 1000 ); 
        });
    } 
    write(PADocument,$ele) {
        PADocument.open();
       // console.log(this.docType() + "" + this.getHead() + this.getBody( $ele ) + "");
        PADocument.write(this.docType() + "" + this.getHead() + this.getBody( $ele ) + "" );
        PADocument.close();
    } 
    docType() {
        if ( this.settings.mode == this.modes.iframe ) return "";

        if ( this.settings.standard == this.standards.html5 ) return "";

        var transitional = this.settings.standard == this.standards.loose ? " Transitional" : "";
        var dtd = this.settings.standard == this.standards.loose ? "loose" : "strict";

        return '';
    } 
    getHead() {
        var extraHead = "";
        var links = "";

        if ( this.settings.extraHead ) this.settings.extraHead.replace( /([^,]+)/g, function(m){ extraHead += m });
        //获取页面当前的';
        });

        //引入的样式布局
        $(document).find("link")
            .filter(function(){ // Requirement:  element MUST have rel="stylesheet" to be considered in print document
                    var relAttr = $(this).attr("rel");
                    return ($.type(relAttr) === 'undefined') == false && relAttr.toLowerCase() == 'stylesheet';
                })
            .filter(function(){ // Include if media is undefined, empty, print or all
                    var mediaAttr = $(this).attr("media");
                    return $.type(mediaAttr) === 'undefined' || mediaAttr == "" || mediaAttr.toLowerCase() == 'print' || mediaAttr.toLowerCase() == 'all'
                })
            .each(function(){
                    links += '';
                });
        if ( this.settings.extraCss ) this.settings.extraCss.replace( /([^,\s]+)/g, function(m){ links += '' });

        return "" + this.settings.popTitle + "" + extraHead + links + "";
    } 
    getBody(elements) {
        var htm = "";
        var attrs = this.settings.retainAttr;
        console.log(elements);
        var ele = this.getFormData(elements); 
        var attributes = ""
        for ( var x = 0; x < attrs.length; x++ )
        {
            var eleAttr = $(ele).attr( attrs[x] );
            if ( eleAttr ) attributes += (attributes.length > 0 ? " ":"") + attrs[x] + "='" + eleAttr + "'";
        }

        htm += '
' + $(ele).html() + '
'; // elements.each(function() { // var ele = this.getFormData( $(this) ); // var attributes = "" // for ( var x = 0; x < attrs.length; x++ ) // { // var eleAttr = $(ele).attr( attrs[x] ); // if ( eleAttr ) attributes += (attributes.length > 0 ? " ":"") + attrs[x] + "='" + eleAttr + "'"; // } // htm += '
' + $(ele).html() + '
'; // }); return "" + htm + ""; } getFormData( ele ) { var copy = ele.clone(); var copiedInputs = $("input,select,textarea", copy); $("input,select,textarea", ele).each(function( i ){ var typeInput = $(this).attr("type"); if ($.type(typeInput) === 'undefined') typeInput = $(this).is("select") ? "select" : $(this).is("textarea") ? "textarea" : ""; var copiedInput = copiedInputs.eq( i ); if ( typeInput == "radio" || typeInput == "checkbox" ) copiedInput.attr( "checked", $(this).is(":checked") ); else if ( typeInput == "text" ) copiedInput.attr( "value", $(this).val() ); else if ( typeInput == "select" ) $(this).find( "option" ).each( function( i ) { if ( $(this).is(":selected") ) $("option", copiedInput).eq( i ).attr( "selected", true ); }); else if ( typeInput == "textarea" ) copiedInput.text( $(this).val() ); }); return copy; } createIframe() { var frameId = this.settings.id; var iframeStyle = 'border:0;position:absolute;width:0px;height:0px;right:0px;top:0px;'; var iframe; try { iframe = document.createElement('iframe'); document.body.appendChild(iframe); $(iframe).attr({ style: iframeStyle, id: frameId, src: "#" + new Date().getTime() }); iframe.doc = null; iframe.doc = iframe.contentDocument ? iframe.contentDocument : ( iframe.contentWindow ? iframe.contentWindow.document : iframe.document); } catch( e ) { throw e + ". iframes may not be supported in this browser."; } if ( iframe.doc == null ) throw "Cannot find document."; return iframe; } } let myPrint = new MyPrint (); export default myPrint;

 

 

你可能感兴趣的:(VUE,前端)