vue 实现导出pdf
Vue 实现导出 PDF 的方法
使用 html2pdf.js 库
安装 html2pdf.js 库:
npm install html2pdf.js
在 Vue 组件中引入并使用:
import html2pdf from 'html2pdf.js'
export default {
methods: {
exportToPDF() {
const element = document.getElementById('pdf-content')
const opt = {
margin: 10,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
}
html2pdf().from(element).set(opt).save()
}
}
}
模板部分:
<template>
<div>
<div id="pdf-content">
<!-- 这里是要导出为 PDF 的内容 -->
<h1>PDF 导出示例</h1>
<p>这是一段测试内容</p>
</div>
<button @click="exportToPDF">导出 PDF</button>
</div>
</template>
使用 jsPDF 和 html2canvas
安装依赖:
npm install jspdf html2canvas
实现代码:
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'
export default {
methods: {
async generatePDF() {
const element = document.getElementById('pdf-content')
const canvas = await html2canvas(element)
const imgData = canvas.toDataURL('image/png')
const pdf = new jsPDF('p', 'mm', 'a4')
const imgWidth = 210
const pageHeight = 295
const imgHeight = canvas.height * imgWidth / canvas.width
let heightLeft = imgHeight
let position = 0
pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
heightLeft -= pageHeight
while (heightLeft >= 0) {
position = heightLeft - imgHeight
pdf.addPage()
pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
heightLeft -= pageHeight
}
pdf.save('document.pdf')
}
}
}
使用 vue-html2pdf 插件
安装插件:
npm install vue-html2pdf
使用示例:
import VueHtml2pdf from 'vue-html2pdf'
export default {
components: { VueHtml2pdf },
methods: {
generateReport() {
this.$refs.html2Pdf.generatePdf()
}
}
}
模板部分:
<template>
<div>
<vue-html2pdf
ref="html2Pdf"
:show-layout="false"
:float-layout="true"
:enable-download="true"
:preview-modal="true"
filename="document"
:paginate-elements-by-height="1400"
:pdf-quality="2"
pdf-format="a4"
pdf-orientation="portrait"
>
<section slot="pdf-content">
<!-- PDF 内容 -->
<h1>PDF 导出示例</h1>
<p>使用 vue-html2pdf 插件</p>
</section>
</vue-html2pdf>
<button @click="generateReport">生成 PDF</button>
</div>
</template>
注意事项
- 确保要导出的内容已经渲染完成
- 对于复杂布局,可能需要调整 html2canvas 的配置
- 中文支持可能需要额外配置字体
- 分页处理需要考虑内容高度
- 图片资源需要确保跨域问题已解决
以上方法提供了不同复杂度的 PDF 导出方案,可以根据项目需求选择合适的实现方式。







