Print.js
有四種打印文檔類型可用:’ pdf ‘,’ html ','圖像’和json。
默認類型是’ pdf '。
它的基本用法是呼叫printJS()只需輸入一個PDF文檔網址:printJS('docs/PrintJS.pdf ')。
對於圖像文件,想法是一樣的,但是您需要傳遞第二個參數:printJS('images/PrintJS.jpg ‘,’ image ‘)。
要打印HTML元素,以類似的方式,傳入元素id並鍵入:printJS(’ myelementtid ‘,’ html ‘)。
打印JSON數據時,傳入要打印的數據、類型和數據屬性: printJS({可打印:myData,類型:’ json ',屬性:[‘prop1
‘,’ prop2 ‘,’ prop3’]});
下載並安裝
npm/yarn安裝
npm install print-js --save
yarn add print-js
在項目中引入
import print from ‘print-js’
用cdn也可以直接引入
https://printjs-4de6.kxcdn.com/print.min.js
https://printjs-4de6.kxcdn.com/print.min.css
入門指南
在需要的文件內引入 <script src="print.js"></script>
如果你使用了modal 需要引入css文件<link rel="stylesheet" type="text/css" href="print.css">
文件打印
添加一個按鈕來打印位於您的托管服務器上的PDF文件:
<button type="button" onclick="printJS('docs/printjs.pdf')">
Print PDF
</button>

對於大文件,您可以在加載文件時向用戶顯示消息
<button type="button" onclick="printJS({printable:'docs/xx_large_printjs.pdf', type:'pdf', showModal:true})">
Print PDF with Message
</button>
支持base64 PDF打印:
<button type="button" onclick="printJS({printable: base64, type: 'pdf', base64: true})">
Print PDF with Message
</button>
HTML打印
有時我們只想打印HTML頁面的選定部分,這可能很棘手。使用Print.js,我們可以輕松地傳遞想要打印的元素的id。元素可以是任何標簽,只要它有唯一的id。該庫將嘗試打印它非常接近它在屏幕上的樣子,同時,它將為它創建一個打印機友好的格式。
表單打印


帶有參數的打印,比如標題
<button type="button" onclick="printJS({ printable: 'printJS-form', type: 'html', header: 'PrintJS - Form Element Selection' })">
Print Form with Header
</button>
圖像打印
圖片打印
printJS('images/print-01-highres.jpg', 'image')
添加頁眉
printJS({printable: 'images/print-01-highres.jpg', type: 'image', header: 'My cool image header'})
打印多個圖片
printJS({
printable: ['images/print-01-highres.jpg', 'images/print-02-highres.jpg', 'images/print-03-highres.jpg'],
type: 'image',
header: 'Multiple Images',
imageStyle: 'width:50%;margin-bottom:20px;'
})
JSON打印
someJSONdata = [
{
name: 'John Doe',
email: 'john@doe.com',
phone: '111-111-1111'
},
{
name: 'Barry Allen',
email: 'barry@flash.com',
phone: '222-222-2222'
},
{
name: 'Cool Dude',
email: 'cool@dude.com',
phone: '333-333-3333'
}
]
基本
<button type="button" onclick="printJS({printable: someJSONdata, properties: ['name', 'email', 'phone'], type: 'json'})">
Print JSON Data
</button>
自定義樣式
<button type="button" onclick="printJS({
printable: someJSONdata,
properties: ['name', 'email', 'phone'],
type: 'json',
gridHeaderStyle: 'color: red; border: 2px solid #3971A5;',
gridStyle: 'border: 2px solid #3971A5;'
})">
Print JSON Data
</button>
自定義表格標題名稱
<button type="button" onclick="printJS({
printable: someJSONdata,
properties: [
{ field: 'name', displayName: 'Full Name'},
{ field: 'email', displayName: 'E-mail'},
{ field: 'phone', displayName: 'Phone'}
],
type: 'json'
})">
Print with custom table header text
</button>
添加表格標題文本
<button type="button" onclick="printJS({
printable: someJSONdata,
type: 'json',
properties: ['name', 'email', 'phone'],
header: '<h3 class="custom-h3">My custom header</h3>',
style: '.custom-h3 { color: red; }'
})">
Print header raw html
</button>
