vue2中Print.js的使用超詳細講解(pdf、html、json、image)
概要
前端實現(xiàn)打?。ò琾df、html、json、image)
安裝
npm install print-js --save
JSON使用
在項目vue文件中引入
import printJS from "print-js";
點擊按鈕時調(diào)用插件方法
<a-button
class="not-print"
@click="handlePrint"
type="primary"
style="margin-top: 20px"
>打印</a-button
> handlePrint(data = this.data) {
console.log(data);
printJS({
// header: '表格標題',
type: "json",
properties: [
{ field: "age", displayName: "年齡" },
{ field: "name", displayName: "姓名" },
{ field: "address", displayName: "地址" },
],
printable: data,
// gridHeaderStyle: 'color: red; border: 2px solid #3971A5;',
// gridStyle: 'border: 2px solid #3971A5;'
header: `<h3 class="custom-h3">${this.title}</h3>`,
style: ".custom-h3 { color: red;text-align:center}",
});
},- type:類型(可以是html pdf image json)
- properties:配置json相關的內(nèi)容(filed要跟json的字段必須一樣?。。。?/li>
- displayName:就是表格的表頭信息
- printable:需要打印的數(shù)據(jù)
- header:可以在表格上方增加一個類似標題信息
- style:配置樣式
圖片使用
printJS({printable: 'images/print-01-highres.jpg', type: 'image', header: 'My image header'})
配置都是類似的,單張寫圖片路徑,多張寫成數(shù)組就可以了
Pdf使用
<button type="button" onclick="printJS('docs/printjs.pdf')">
Print PDF
</button>還可以為base64格式
<button type="button" onclick="printJS({printable: base64, type: 'pdf', base64: true})">
Print PDF with Message
</button>最實用的來了
小編在工作需求中是遇到了打印各種混合的類型,比如說一個表格里面有圖片,其他信息等。因為圖片是后端返回來的鏈接,一開始用JSON格式打印出來是表格的形式,圖片這一塊就是個鏈接地址,并沒有跟我們想的一樣是圖片
后來參考Print.js的官網(wǎng),研究了一下,發(fā)現(xiàn)以html形式打印,它會將你整個頁面打印出來。這才是我們想要的格式
Print.js官網(wǎng):
Print.js官網(wǎng):https://printjs.crabbly.com/
<button type="button" onclick="printJS({ printable: 'printJS-form', type: 'html', header: 'PrintJS - Form Element Selection' })">
Print Form with Header
</button>注意此時的printable配置不再是跟JSON、image一樣的數(shù)據(jù)了。這里需要的是一個唯一的元素id,
例如
<a-drawer title="Basic Drawer" placement="right" :closable="false" :visible="visibleD"
:after-visible-change="afterVisibleChange" @close="onClose" width="50%" :maskClosable="true">
<div id="basic">
<div v-for="item in 4">
<a-card hoverable style="width: 240px">
<img slot="cover" alt="example" src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png" />
<a-card-meta title="Europe Street beat">
<template slot="description">
www.instagram.com
</template>
</a-card-meta>
</a-card>
</div>
</div>
<div>
<a-button @click="printSure">確定打印</a-button>
</div>
</a-drawer>這里的basic就是我要打印的一個id,可以將需要打印的頁面寫在這個地方,循環(huán)遍歷渲染數(shù)據(jù),這樣就很方便了。
demo示例

總結(jié)
到此這篇關于vue2中Print.js使用的文章就介紹到這了,更多相關vue2中Print.js使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue2實現(xiàn)子組件修改父組件值的方法小結(jié)
在 Vue 2 中,子組件不能直接修改父組件的值,因為 Vue 遵循單向數(shù)據(jù)流的原則,為了實現(xiàn)子組件修改父組件的數(shù)據(jù),本文給大家介紹了Vue2實現(xiàn)子組件修改父組件值的四種方法,并通過代碼示例講解的非常詳細,需要的朋友可以參考下2025-03-03

