Print.js 学习 Day5 2018-11-23
2018-11-23 本文已影响0人
Ernest_Chou
今天合并了项目发布,调试时发现部署项目后用点击打印出现打印空白的bug,但不部署直接访问页面能正常打印。研究了好久,感觉调用打印方法时可能存在加载延迟或者异步之类的bug,无法确定原因。
从网上找到一些答案,刚好GitHub上bug被修复了,在这里总结一下。
1.点击打印空白原因及解决方法
代码逻辑里iframe加载与打印是异步执行的,很容易导致在document.execCommand('print')
的时候,还没加载出来,所以是一片空白。针对修改在trycatch外层加上打印窗口window的onload(必须等到页面内包括图片的所有元素加载完毕后才能执行)回调,保证页面加载渲染完成再打印。
2.简单注释:
2.1 主函数:
初始化打印dom,排除非打印区域
2.2 原型链:
- init:调用链方法getStyle和getHtml将样式与dom字符串组装起来 write将该组装片段写入中
- extend:对象浅层扩展封装
- getStyle:从当前页面获取style标签和link标签 附加no-print隐藏样式 以写入
- getHtml:获取主函数中附着在this原型上的指定dom对象 并且将当前input、textarea、select的状态、内容二次赋值,以便在写入的时候能渲染出一样的结果
-
write:将组装好的html字符串写入的DOM,其中
doc.open()
为打开写入文档流,才能写入内容,doc.close()
为关闭写入文档流,以结束的load状态,其他的应该不难理解。
3. Print.js插件源码
/* @Print.js
* 2018-11-23
*/
(function (window, document) {
var Print = function (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;
}(window, document));
4. 使用示例:
4.1 直接绑定使用
//有回调函数的使用
clickPrint(id) {
Print(id, {
onStart: function () {
console.log('onStart', new Date())
},
onEnd: function () {
console.log('onEnd', new Date())
}
})
}
<div id="table1" class="table-box">
<el-table :data="tableData1" stripe style="width: 100%">
<el-table-column type="index" label="序号" align="center"></el-table-column>
<el-table-column prop="casherId" label="人员号" align="center"></el-table-column>
<el-table-column prop="name" label="姓名" align="center"></el-table-column>
<el-table-column prop="invoiceVersionNum" label="版本号" align="center"></el-table-column>
<el-table-column prop="minInvoiceNum" label="最小机制号" align="center"></el-table-column>
<el-table-column prop="maxReceiptNum" label="最大机制号" align="center"></el-table-column>
<el-table-column prop="maxInvoiceNum" label="最大号" align="center"></el-table-column>
<el-table-column prop="minInvoiceNum" label="最小号" align="center"></el-table-column>
<el-table-column prop="usedNum" label="数量" align="center"></el-table-column>
<el-table-column prop="invalidNum" label="作废票数" align="center"></el-table-column>
</el-table>
<!--<button class="btn no-print" @click="Print('#table1')">打印</button>-->
<button class="btn no-print" @click="clickPrint('#table1')">打印</button>
</div>
4.2 vue.js中根据ref指定调用
Vue.prototype.$print = Print;
clickPrint() {
this.$print(this.$refs.table1);//table1 表示ref名称
}
<div ref="table1" class="table-box">
<el-table :data="tableData1" stripe style="width: 100%">
<el-table-column type="index" label="序号" align="center"></el-table-column>
<el-table-column prop="casherId" label="人员号" align="center"></el-table-column>
<el-table-column prop="name" label="姓名" align="center"></el-table-column>
<el-table-column prop="invoiceVersionNum" label="版本号" align="center"></el-table-column>
<el-table-column prop="minInvoiceNum" label="最小机制号" align="center"></el-table-column>
<el-table-column prop="maxReceiptNum" label="最大机制号" align="center"></el-table-column>
<el-table-column prop="maxInvoiceNum" label="最大号" align="center"></el-table-column>
<el-table-column prop="minInvoiceNum" label="最小号" align="center"></el-table-column>
<el-table-column prop="usedNum" label="数量" align="center"></el-table-column>
<el-table-column prop="invalidNum" label="作废票数" align="center"></el-table-column>
</el-table>
<button class="btn no-print" @click="clickPrint">打印</button>
</div>