在最近做项目的时候,遇到一个需求需要能预览简历并导出成pdf,这里我记录下将html导出pdf的方法。
引入导出pdf需要用到的html2canvas与jspdf:
- npm install html2canvas
- npm install jspdf
这里我封装成一个方法在需要用到的地方直接调用就可以,下面直接上代码:
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
/**
* 处理导出pdf
* */
export const handleExportPdfByHtml = (selectors, title) => {
html2Canvas(document.querySelector(selectors), {
allowTaint: true,
}).then(canvas => {
// DOM生成base64图片
const base64Image = canvas.toDataURL('image/jpeg', 1);
// 图片的大小
const contentWidth = canvas.width;
const contentHeight = canvas.height;
// 每一页的尺寸 - A1尺寸
const pageWidth = 594;
const pageHeight = 841;
// DOM缩放比例后的高度
const imageHeight = pageWidth / contentWidth * contentHeight;
// 创建PDF对象
const PDF = new JsPDF('p', 'pt', 'a4');
// 当前高度只需要打印一页
if (imageHeight < pageHeight) {
PDF.addImage(base64Image, 'JPEG', 0, 0, pageWidth, imageHeight)
}
// 高度过高打印多页
else {
let tempHeight = imageHeight;
for(let i = 0; tempHeight > 0; i++) {
PDF.addImage(base64Image, 'JPEG', 0, -i * pageHeight, pageWidth, imageHeight);
tempHeight -= pageHeight;
if(tempHeight > 0) {
PDF.addPage();
}
}
}
PDF.save(title + '.pdf')
});
}
使用:
<template>
<div style="width: 700px; margin: auto;">
<div id="content" style="background: #0BB7AF;">
<p v-for="(item, index) in 100" :key="index">内容{{index + 1}}</p>
</div>
<button @click="handleExportPdfByHtml('#content', '文件标题')">按钮</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { handleExportPdfByHtml } from '@/utils/common';
export default defineComponent({
components: {},
setup() {
return {
handleExportPdfByHtml,
}
}
});
</script>
效果: