一、需要用到两个插件,需要安装
vue框架中实现导出pdf
javascript
npm install --save html2canvas // Dom转canvas再转image
npm install jspdf --save // image转pdf
二、实现方法
分别获取每个页面的DOM元素,并转为canvas再转image,通过jsPDF插件把图片添加进来,再实现导出即可
jsPDF提供了一个很有用的API,addPage(),我们可以通过pdf.addPage(),来添加一页pdf,然后通过pdf.addImage(...),将图片赋予这页pdf来显示。
三、完整代码
javascript
<template>
<div class="main">
<el-button @click="download">下载</el-button>
<div id="page1">
<img src="@/assets/images/page1.png" alt="page1" />
</div>
<div id="page2">
<img src="@/assets/images/page2.png" alt="page2" />
</div>
<div id="page3">
<img src="@/assets/images/page3.png" alt="page3" />
</div>
</div>
</template>
<script setup lang="ts">
import JsPDF from "jspdf";
import html2canvas from "html2canvas";
const download = () => {
let pageDom1 = document.getElementById("page1") as HTMLElement;
let pageDom2 = document.getElementById("page2") as HTMLElement;
let pageDom3 = document.getElementById("page3") as HTMLElement;
let listDom = [html2canvas(pageDom1), html2canvas(pageDom2), html2canvas(pageDom3)]; // dom转canvas
Promise.all(listDom).then(canvasList => {
let pdf = new JsPDF("p", "pt", "a4");
canvasList.forEach((canvas, index) => {
let imgData = canvas.toDataURL("image/png"); // canvas转图片
pdf.addImage(imgData, "PNG", 0, 0, 595, 842); // 595 842 a4纸宽高
if (index < canvasList.length - 1) {
pdf.addPage(); // 添加新页面
}
});
pdf.save("download.pdf"); // 导出
window.history.go(-1); // 关闭当前页面
});
};
</script>
<style scoped lang="scss">
.main {
width: 595px;
margin: 0 auto;
img {
display: block;
width: 595px;
height: 842px;
}
}
</style>