插件官網地址:vue-print-nb - npm
1.安裝
npm install vue-print-nb --save
2.導入打印插件?
//main.js
import Print from 'vue-print-nb'
Vue.use(Print);
3.配置參數
4.頁面使用
<div id="printDiv">打印內容</div><el-button v-print="'#printDiv'">打印</el-button>或<el-button v-print="'printConfig'">打印</el-button>
<script>
export default {data() {return {printConfig:{id:'printPage', //被打印部分的id popTitle: '配置頁眉標題', // 打印配置頁上方的標題extraHead: '打印', // 最上方的頭部文字,附加在head標簽上的額外標簽,使用逗號分割preview: true, // 是否啟動預覽模式,默認是falsepreviewTitle: '預覽的標題', // 打印預覽的標題previewPrintBtnLabel: '預覽結束,開始打印', // 打印預覽的標題下方的按鈕文本,點擊可進入打印zIndex: 20002, // 預覽窗口的z-index,默認是20002,最好比默認值更高previewBeforeOpenCallback () { console.log('正在加載預覽窗口!'); console.log(that.msg, this) }, // 預覽窗口打開之前的callbackpreviewOpenCallback () { console.log('已經加載完預覽窗口,預覽打開了!') }, // 預覽窗口打開時的callbackbeforeOpenCallback () { console.log('開始打印之前!') }, // 開始打印之前的callbackopenCallback () { console.log('執行打印了!') }, // 調用打印時的callbackcloseCallback () { console.log('關閉了打印工具!') }, // 關閉打印的callback(無法區分確認or取消)clickMounted () { console.log('點擊v-print綁定的按鈕了!') },// url: 'http://localhost:8080/', // 打印指定的URL,確保同源策略相同// asyncUrl (reslove) {// setTimeout(() => {// reslove('http://localhost:8080/')// }, 2000)// },standard: '',extarCss: ''},}}
}
</script>
5.打印樣式設置
<style scoped media="print">/*指定打印的分頁*//deep/ section{page-break-after:always;}/*避免出現空白尾頁*/html,body,#app{height: 98% !important;margin: 0px;padding: 0px;}
</style>
設置打印內容樣式,不影響頁面原有樣式 以下內容為設置? element table? 在打印時的樣式,防止打印不全
@page {size: auto;margin: 3mm;
}
@media print {html {background-color: #ffffff;height: auto;margin: 0px;}body {border: solid 1px #ffffff;/* margin: 10mm 15mm 10mm 15mm; */}#print table {table-layout: auto !important;}#print .el-table__header-wrapper .el-table__header {width: 100% !important;border: solid 1px #f2f2f2;}#print .el-table__body-wrapper .el-table__body {width: 100% !important;border: solid 1px #f2f2f2;}#print #pagetable table {table-layout: fixed !important;}#print .el-table__empty-block {width: 100% !important;height: auto !important;}#print .el-input-number--small{width: 100% !important;}}
6.分頁
在要進行分頁訛標簽上,添加以下樣式
page-break-after:always
例如:
<div id="printPage"><section>第一頁的內容</section><section>第二頁的內容</section>
</div><style>
section{page-break-after: always;
}
</style>
或者 在需要分頁的內容最后加上
<p style="page-break-after: always;"></p>
7.移除末尾的空白頁
若打印時,末尾總是出現空白頁,則存在定義了height:100%的元素,刪除掉此央視即可通常都是因為存在以下樣式導致,通常被定義在全局樣式文件中,或index.html中
html,body,#app{height: 100%}
8.隱藏打印區域中的某個div
您可以通過在需要隱藏的div上添加??class="no-print"?,然后在打印樣式中設置該類的?display屬性為?none?來實現隱藏。具體步驟如下:
1.在需要隱藏的div上(測試 必須是div標簽)添加??class="no-print"?,例如:
<div class="no-print">這是需要隱藏的內容
</div>
2.在打印樣式中設置該類的display屬性為none,例如:
@media print {.no-print {display: none;}
}
這樣,在打印預覽或者實際打印時,帶有? class="no-print"??的div就會被隱藏掉。
9.window.print() 瀏覽器打印功能
js 執行 window.print() 就會調用谷歌瀏覽器的打印功能。