插件文檔:https://printjs.com/
npm文檔: https://www.npmjs.com/package/print-js
npm install print-js --save
在需要列印功能的組建中
import print from 'print-js'
通用寫法:
<div id="printContent"> 列印這些html</div>
<button @click="openPrint()">點選列印</button>
openPrint(){
printJS({
printable: 'printContent',// // 文檔來源:pdf或圖像的url,html元素的id或json資料的對象
type: 'json', // 可列印的類型。可用的列印選項包括:pdf,html,圖像,json和raw-html。
targetStyles: ['*'] // 庫在列印HTML元素時處理任何樣式
})
}
為什麼選擇print.js
1.剛開始寫列印功能的時候,先百度一下。找了一些單純的js寫法來實作:
手動建立一個iframe,列印這個iframe的内容
openPrint(){
//判斷iframe是否存在,不存在則建立iframe
var iframe=document.getElementById("printContent");
if(!iframe){
var el = document.getElementById("printcontent");
iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute("id", "print-iframe");
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-999em;top:-500px;');
//left負值不會出現橫向滾動條
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
//這裡可以自定義樣式
//doc.write("<LINK rel="stylesheet" type="text/css" href="css/print.css" target="_blank" rel="external nofollow" >");
doc.write('<div>' + el.innerHTML + '</div>');
doc.close();
iframe.contentWindow.focus();
}
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0){
document.body.removeChild(iframe);
}
}
問題:當列印機構複雜的包含圖檔、文字、表情的html,會有部分樣式丢失。
于是開始考慮找列印插件
2.首先以vue為前提找到了vue-print-nb
npm文檔:https://www.npmjs.com/package/vue-print-nb
npm install vue-print-nb --save
在main.js中引入
import Print from 'vue-print-nb'
Vue.use(Print);
之後在元件寫列印某些内容的時候可以直接寫
<div id="printContent"> 列印這些html</div>
<button v-print="#printContent">點選列印</button>
或者
<div id="printContent"> 列印這些html</div>
<button v-print="openPrint">點選列印</button>
export default {
data() {
return {
openPrint: {
id: "printContent",
popTitle: '列印的标題',
extraCss: 'https://www.google.com,https://www.google.com',
extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>'
}
};
}
}
問題:
- 當列印機構複雜的包含圖檔、文字、表情和多張背景圖檔的html,會有部分樣式丢失。導緻背景圖檔超出原來位置,按原圖大小展示。
- 列印的内容比較多,浏覽器出現滾動條時,隻能列印目前可視視窗的内容
這個插件,書寫簡潔。适合列印資料結構不複雜的内容。複雜的内容列印時,暫未發現如何解決以上内容