vue前端實(shí)現(xiàn)打印下載示例詳解
html2canvas介紹
分享一下幾個(gè)后臺(tái)管理系統(tǒng)比較常用的插件:下載、打印
html2canvas是在瀏覽器上對網(wǎng)頁進(jìn)行截圖操作,實(shí)際上是操作DOM,這個(gè)插件也有好長時(shí)間了,比較穩(wěn)定,目前使用還沒有遇到什么bug

jspdf介紹
如果下載出來是pdf文件,可以加上jspdf插件,會(huì)先通過html2canvas把頁面轉(zhuǎn)化成base64圖片,再通過jspdf導(dǎo)出

安裝
npm i html2canvas jspdf 或 yarn add html2canvas jspdf
使用
<template>
<div>
<h1 ref="toPdf">
導(dǎo)出區(qū)域
</h1>
<button @click="toPdfFn">導(dǎo)出pdf</button>
</div>
</template>
<script>
import html2canvas from "html2canvas"
import JSPDF from "jspdf"
export default {
methods:{
toPdfFn(){
this.htmlToPdf('文件名','時(shí)間')
},
htmlToPdf(name,time){
let element = this.$refs.toPdf
html2canvas(element, {
logging: false
}).then(function(canvas) {
let pdf = new JSPDF("p", "mm", "a4") // A4紙,縱向
let ctx = canvas.getContext("2d")
let a4w = 190;
let a4h = 277 // A4大小,210mm x 297mm,四邊各保留20mm的邊距,顯示區(qū)域190x277
let imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4顯示比例換算一頁圖像的像素高度
let renderedHeight = 0
while (renderedHeight < canvas.height) {
let page = document.createElement("canvas")
page.width = canvas.width
page.height = Math.min(imgHeight, canvas.height - renderedHeight) // 可能內(nèi)容不足一頁
// 用getImageData剪裁指定區(qū)域,并畫到前面創(chuàng)建的canvas對象中
page.getContext("2d").putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight,
canvas.height - renderedHeight)), 0, 0)
pdf.addImage(page.toDataURL("image/jpeg", 1.0), "JPEG", 10, 10, a4w, Math.min(a4h, a4w * page.height /
page.width)) // 添加圖像到頁面,保留10mm邊距
// 如果后面還有內(nèi)容,添加一個(gè)空頁
renderedHeight += imgHeight
if (renderedHeight < canvas.height) {
pdf.addPage()
}
}
pdf.save(name + time)
})
}
}
}
</script>
注意點(diǎn):
1、能使用ref來獲取html結(jié)構(gòu)就用ref,盡量不使用id。如果使用的地方比較多可以掛載到vue實(shí)例上
2、導(dǎo)出的pdf空白情況:檢查dom結(jié)構(gòu)有沒有獲取到,還有就是css樣式要寫在導(dǎo)出區(qū)域內(nèi)的元素中
printjs介紹
之前是使用vue-print-nb插件的,但是這個(gè)插件有點(diǎn)貓病,有時(shí)候會(huì)出現(xiàn)樣式跨域的問題,有時(shí)候又正常,后面在GitHub上找到的一個(gè),用到現(xiàn)在也沒出現(xiàn)過什么問題
在utils文件里面創(chuàng)建一個(gè)print.js文件
// 打印類屬性、方法定義
/* eslint-disable */
const Print = function (dom, options) {
if (!(this instanceof Print)) return new Print(dom, options);
this.options = this.extend({
'noPrint': '.no-print'
}, options);
if ((typeof dom) === "string") {
this.dom = document.querySelector(dom);
} else {
this.isDOM(dom)
this.dom = this.isDOM(dom) ? dom : dom.$el;
}
this.init();
};
Print.prototype = {
init: function () {
var content = this.getStyle() + this.getHtml();
this.writeIframe(content);
},
extend: function (obj, obj2) {
for (var k in obj2) {
obj[k] = obj2[k];
}
return obj;
},
getStyle: function () {
var str = "",
styles = document.querySelectorAll('style,link');
for (var i = 0; i < styles.length; i++) {
str += styles[i].outerHTML;
}
str += "<style>" + (this.options.noPrint ? this.options.noPrint : '.no-print') + "{display:none;}</style>";
return str;
},
getHtml: function () {
var inputs = document.querySelectorAll('input');
var textareas = document.querySelectorAll('textarea');
var selects = document.querySelectorAll('select');
for (var k = 0; k < inputs.length; k++) {
if (inputs[k].type == "checkbox" || inputs[k].type == "radio") {
if (inputs[k].checked == true) {
inputs[k].setAttribute('checked', "checked")
} else {
inputs[k].removeAttribute('checked')
}
} else if (inputs[k].type == "text") {
inputs[k].setAttribute('value', inputs[k].value)
} else {
inputs[k].setAttribute('value', inputs[k].value)
}
}
for (var k2 = 0; k2 < textareas.length; k2++) {
if (textareas[k2].type == 'textarea') {
textareas[k2].innerHTML = textareas[k2].value
}
}
for (var k3 = 0; k3 < selects.length; k3++) {
if (selects[k3].type == 'select-one') {
var child = selects[k3].children;
for (var i in child) {
if (child[i].tagName == 'OPTION') {
if (child[i].selected == true) {
child[i].setAttribute('selected', "selected")
} else {
child[i].removeAttribute('selected')
}
}
}
}
}
return this.dom.outerHTML;
},
writeIframe: function (content) {
var w, doc, iframe = document.createElement('iframe'),
f = document.body.appendChild(iframe);
iframe.id = "myIframe";
//iframe.style = "position:absolute;width:0;height:0;top:-10px;left:-10px;";
iframe.setAttribute('style', 'position:absolute;width:0;height:0;top:-10px;left:-10px;');
w = f.contentWindow || f.contentDocument;
doc = f.contentDocument || f.contentWindow.document;
doc.open();
doc.write(content);
doc.close();
var _this = this
iframe.onload = function(){
_this.toPrint(w);
setTimeout(function () {
document.body.removeChild(iframe)
}, 100)
}
},
toPrint: function (frameWindow) {
try {
setTimeout(function () {
frameWindow.focus();
try {
if (!frameWindow.document.execCommand('print', false, null)) {
frameWindow.print();
}
} catch (e) {
frameWindow.print();
}
frameWindow.close();
}, 10);
} catch (err) {
console.log('err', err);
}
},
isDOM: (typeof HTMLElement === 'object') ?
function (obj) {
return obj instanceof HTMLElement;
} :
function (obj) {
return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';
}
};
const MyPlugin = {}
MyPlugin.install = function (Vue, options) {
// 4. 添加實(shí)例方法
Vue.prototype.$print = Print
}
export default MyPlugin
printjs源碼在這里
在main.js中注冊
import Vue from "vue"; import print from "./src/utils/print.js"; Vue.use(print)
在需要的地方使用
<template>
<div>
<h1 ref="print">
<div>打印區(qū)域</div>
</h1>
<button @click="printFn">打印</button>
</div>
</template>
<script>
export default {
methods: {
printFn() {
//傳入dom結(jié)構(gòu)即可
this.$print(this.$refs.print);
},
},
};
</script>

注意:需使用ref獲取dom節(jié)點(diǎn),若直接通過id或class獲取則webpack打包部署后打印內(nèi)容為空
指定不打印區(qū)域 方法
方法一. 添加no-print樣式類
<div class="no-print">不要打印我</div>
方法二. 自定義類名
<div class="do-not-print-me-xxx">不要打印我</div>
this.$print(this.$refs.print,{'no-print':'.do-not-print-me-xxx'}) // 使用以上就是vue前端實(shí)現(xiàn)打印下載示例詳解的詳細(xì)內(nèi)容,更多關(guān)于vue前端打印下載的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue?2源碼閱讀?Provide?Inject?依賴注入詳解
這篇文章主要為大家介紹了Vue?2源碼閱讀?Provide?Inject?依賴注入詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
Vue實(shí)現(xiàn)dom元素拖拽并限制移動(dòng)范圍的操作代碼
這篇文章主要介紹了Vue實(shí)現(xiàn)dom元素拖拽并限制移動(dòng)范圍的操作代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-12-12
在vue-cli項(xiàng)目中使用bootstrap的方法示例
本篇文章主要介紹了在vue-cli項(xiàng)目中使用bootstrap的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04
Vue中使用provide和inject實(shí)例對比分析
這篇文章主要為大家介紹了Vue中使用provide和inject實(shí)例對比分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
Vue拖動(dòng)截圖功能的簡單實(shí)現(xiàn)方法
最近項(xiàng)目上要做一個(gè)車牌識(shí)別的功能,就需要做拖動(dòng)截圖功能了,因?yàn)榍岸问莢ue,所以下面這篇文章主要給大家介紹了關(guān)于Vue拖動(dòng)截圖功能的簡單實(shí)現(xiàn)方法,需要的朋友可以參考下2021-07-07
如何實(shí)現(xiàn)一個(gè)簡易版的vuex持久化工具
這篇文章主要介紹了實(shí)現(xiàn)一個(gè)簡易版的vuex持久化工具,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09

