1、安装
npm install --save html2canvas
npm install --save jspdf
2、使用
<template>
<el-card class="mb15">
<template #header>
<span>jspdf</span>
</template>
<div ref="badge" class="badge">
<el-calendar v-model="value" />
</div>
<div style="margin: 20px 0">
<el-button type="primary" size="default" @click="exportPDF">生成pdf</el-button>
</div>
</el-card>
</template>
<script setup lang="ts" name="demoView">
import { ref } from 'vue';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
const value = ref(new Date())
const badge = ref();
const exportPDF = () => {
html2canvas(badge.value, {
logging: false,
bgcolor: '#ffffff',
useCORS: true,
// scale: 2, // 缩放
// dpi: 96, // 分辨率
}).then((canvas) => {
const contentWidth = canvas.width;
const contentHeight = canvas.height;
const pageHeight = (contentWidth / 592.28) * 841.89;
let leftHeight = contentHeight;
// 页面偏移
let position = 0;
// a4纸的尺寸[595.28,841.89]
// canvas在pdf里的宽高
const imgWidth = 595.28;
const imgHeight = (imgWidth / contentWidth) * contentHeight;
/* const ctx = canvas.getContext('2d');
// 添加水印
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.rotate((25 * Math.PI) / 180);
ctx.font = '20px Microsoft Yahei';
ctx.fillStyle = 'rgba(184, 184, 184, 0.8)';
for (let i = contentWidth * -1; i < contentWidth; i += 240) {
for (let j = contentHeight * -1; j < contentHeight; j += 100) {
// 填充文字,x 间距, y 间距
ctx.fillText('磊哥', i, j);
}
} */
const pageData = canvas.toDataURL('image/jpeg', 1.0);
const pdf = new jsPDF('', 'pt', 'a4');
if (leftHeight < pageHeight) {
// 在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示;
pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
} else {
// 分页
while (leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= 841.89;
// 避免添加空白页
if (leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save(`文件名.pdf`);
});
};
</script>
<style lang="scss" scoped>
</style>
3、效果
4、封装成一个方法
// 生成报表(dom中存在图片且图片路径跨域 需为img元素添加 crossorigin="anonymous" )
async function htmlToPDF({ id, title = "报表", bgColor = "#fff" }) {
const A4Width = 595.28;
const A4Height = 841.89;
let canvas = await html2canvas(document.getElementById(id), {
scale: 2,
useCORS: true,
backgroundColor: bgColor,
});
let pageHeight = (canvas.width / A4Width) * A4Height;
let leftHeight = canvas.height;
let position = 0;
let imgWidth = A4Width;
let imgHeight = (A4Width / canvas.width) * canvas.height;
let pageData = canvas.toDataURL("image/jpeg", 1.0);
let PDF = new jspdf.jsPDF("", "pt", "a4");
if (leftHeight < pageHeight) {
PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= A4Height;
if (leftHeight > 0) PDF.addPage();
}
}
PDF.save(title + ".pdf");
}
使用的时候:htmlToPDF({ id: "PrintBox", title: "点位二维码" })