直接用【print-js】實(shí)現(xiàn)打印,有些樣式不能正常識(shí)別特漩。所以用html2canvas將dom轉(zhuǎn)圖片再實(shí)現(xiàn)打印兼容性才是最好的督笆。
注意:利用html2canvas打印圖片,一行文本有可能中間被分割跨兩個(gè)頁面摄狱,這時(shí)需要用css設(shè)置div內(nèi)外邊距來解決。如果內(nèi)容不確定无午,這個(gè)問題很難解決媒役。純print-js打印html,又有很多css樣式錯(cuò)亂或不支持宪迟,只能調(diào)整css樣式解決兼容(工作量大)酣衷。
1.安裝兩個(gè)插件:
npm install print-js --save
npm install --save html2canvas
【html2canvas】用法:(注)給dom設(shè)置width寬度(或添加類名控制打印時(shí)的樣式),再執(zhí)行畫布函數(shù)次泽。瀏覽器保存PDF文檔可視內(nèi)容也是710像素左右穿仪。
//html2canvas配置文檔:https://allenchinese.github.io/html2canvas-docs-zh-cn/docs/html2canvas-configuration.html
document.body.style.width = '710px';
html2canvas(document.body, {
backgroundColor: '#ffffff',
}).then((canvas) => {
// toDataURL 圖片格式轉(zhuǎn)成 base64
let dataURL = canvas.toDataURL('image/png');
});
【print-js】用法:
//官網(wǎng)https://printjs.crabbly.com/
printJs({
printable: base64_dataURL,// pdf or image url, html element id or json data object
//printable:['https://www.baidu.com/img/flexible/logo/pc/result.png','https://www.baidu.com/img/flexible/logo/pc/result.png'],//支持多張圖片
type: "image",
maxWidth: 1000,
base64: true,
style: `@media print { @page {size: auto;} body{margin:0px 5px}}` // 解決出現(xiàn)多頁打印時(shí)第一頁空白問題
});
【element-ui + vue2】項(xiàng)目的實(shí)現(xiàn)打印的代碼:
<template>
<div class="container">
<div @click="handlePrint">打印按鈕</div>
<div></div>
<div id="BaseTableBox">要打印的內(nèi)容</div>
<div></div>
</div>
</template>
<script>
import printJs from "print-js"; //導(dǎo)入
import html2canvas from "html2canvas"; //導(dǎo)入
export default {
data() {
return {};
},
created() {},
methods: {
//打印
handlePrint() {
// const loading = this.$loading({
// lock: true,
// text: "正在啟動(dòng)打印",
// spinner: "el-icon-loading",
// background: "rgba(255, 255, 255, 1)",
// });
// let dom = this.$el.querySelector("#BaseTableBox");
let dom = document.querySelector("#BaseTableBox");
dom.classList.add("BaseTablePrint"); //添加打印的布局樣式
let timer = setTimeout(() => {
//添加class樣式不能馬上生效席爽,所以用定時(shí)器延遲,保證樣式生效后再用畫布繪制啊片。
html2canvas(dom, {
backgroundColor: "#ffffff",
}).then((canvas) => {
// loading.close();//關(guān)閉element-ui的加載遮罩
// toDataURL 圖片格式轉(zhuǎn)成 base64
let dataURL = canvas.toDataURL("image/png");
//打印
printJs({
printable: dataURL,
type: "image",
maxWidth: 1000,
base64: true,
style: `@media print { @page {size: auto;} body{margin:0px 5px}}` // 解決出現(xiàn)多頁打印時(shí)第一頁空白問題
});
dom.classList.remove("BaseTablePrint"); //刪除打印的布局樣式
clearTimeout(timer);
});
}, 300);
},
},
};
</script>
<style lang="scss">
.BaseTablePrint {
//打印的樣式
width:710px;
}
</style>
注意:【@media print】媒體查詢的樣式只锻,在edge瀏覽器中,只有用瀏覽器快捷式【Ctrl + P】啟動(dòng)打印print css樣式才會(huì)生效紫谷。