Vue實(shí)現(xiàn)將頁面區(qū)域?qū)С鰹閜df
背景
將前端頁面指定區(qū)域的內(nèi)容導(dǎo)出為pdf,使用純前端實(shí)現(xiàn)
兩種實(shí)現(xiàn)
方式一
使用jsPDF、html2canvas,將特定區(qū)域使用html2canvas轉(zhuǎn)化為圖片,使用jsPDF將圖片轉(zhuǎn)化為pdf。
該方式適用于小區(qū)域轉(zhuǎn)化pdf。當(dāng)前轉(zhuǎn)化區(qū)域有翻頁時(shí)會(huì)出現(xiàn)內(nèi)容拆分導(dǎo)致導(dǎo)致的可讀性變差。
<template>
<div>
<!-- 其他代碼 -->
<el-button @click="handleDownload">下載PDF</el-button>
<el-dialog :visible.sync="dialogVisible">
<div id="content-to-pdf">
<!-- 對(duì)話框內(nèi)容 -->
</div>
</el-dialog>
</div>
</template>
<script>
import html2canvas from 'html2canvas';
import { jsPDF } from "jspdf";
export default {
data() {
return {
dialogVisible: false,
};
},
methods: {
handleDownload() {
const contentDom = document.getElementById('content-to-pdf');
// 使用html2canvas捕獲DOM元素為圖片
html2canvas(contentDom).then(canvas => {
const imgData = canvas.toDataURL('image/png');
// 創(chuàng)建PDF并添加圖片
const pdf = new jsPDF();
pdf.addImage(imgData, 'PNG', 10, 10);
// 下載PDF
pdf.save("download.pdf");
});
}
}
}
</script>
方式二
html2pdf.js將特定區(qū)域。支持自動(dòng)分頁
<template>
<div>
<!-- 其他代碼 -->
<el-button @click="handleDownload">下載PDF</el-button>
<el-dialog :visible.sync="dialogVisible">
<div id="content-to-pdf">
<!-- 對(duì)話框內(nèi)容 -->
</div>
</el-dialog>
</div>
</template>
<script>
import html2pdf from 'html2pdf.js';
export default {
data() {
return {
dialogVisible: false,
};
},
methods: {
handleDownload() {
const contentDom = document.getElementById('content-to-pdf');
html2pdf()
.from(element)
.set({
margin: 10,
filename: '導(dǎo)出文檔.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: {
scale: 2,
useCORS: true, // 如果你有加載圖片,且跨域
allowTaint: true
},
jsPDF: {
unit: 'mm',
format: 'a4',
orientation: 'portrait'
}
})
.save();
}
}
}
</script>
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue+vux?vux安裝出現(xiàn)錯(cuò)誤問題及解決
這篇文章主要介紹了vue+vux?vux安裝出現(xiàn)錯(cuò)誤問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
vue+vuex+axio從后臺(tái)獲取數(shù)據(jù)存入vuex實(shí)現(xiàn)組件之間共享數(shù)據(jù)
這篇文章主要介紹了vue+vuex+axio從后臺(tái)獲取數(shù)據(jù)存入vuex,組件之間共享數(shù)據(jù),非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-04-04
詳解Vue SSR( Vue2 + Koa2 + Webpack4)配置指南
這篇文章主要介紹了詳解Vue SSR( Vue2 + Koa2 + Webpack4)配置指南,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-11-11
vue+element模態(tài)框中新增模態(tài)框和刪除功能
這篇文章主要介紹了vue+element模態(tài)框中新增模態(tài)框和刪除功能,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
vue?eslint報(bào)錯(cuò)error?"Component?name?"*****"
這篇文章主要給大家介紹了關(guān)于vue?eslint報(bào)錯(cuò)error?“Component?name?“*****“?should?always?be?multi-word”的解決方法,文中通過圖文以及實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09
vue路由$router.push()使用query傳參的實(shí)際開發(fā)使用
在vue項(xiàng)目中我們用函數(shù)式編程this.$router.push跳轉(zhuǎn),用query傳遞一個(gè)對(duì)象時(shí)要把這個(gè)對(duì)象先轉(zhuǎn)化為字符串,然后在接收的時(shí)候要轉(zhuǎn)化為對(duì)象,下面這篇文章主要給大家介紹了關(guān)于vue路由$router.push()使用query傳參的實(shí)際開發(fā)使用,需要的朋友可以參考下2022-11-11

