vue实现转成pdf实现打印功能
使用html2canvas和jspdf实现Vue转PDF
安装依赖库
npm install html2canvas jspdf
创建PDF生成工具函数
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
export const exportToPDF = (element, filename = 'document.pdf') => {
html2canvas(element).then(canvas => {
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(filename)
})
}
在Vue组件中使用
<template>
<div ref="content">
<!-- 需要转换为PDF的内容 -->
</div>
<button @click="generatePDF">导出PDF</button>
</template>
<script>
import { exportToPDF } from './pdfUtils'
export default {
methods: {
generatePDF() {
exportToPDF(this.$refs.content, 'my-document.pdf')
}
}
}
</script>
使用vue-html2pdf插件
安装插件
npm install vue-html2pdf
在组件中使用
<template>
<div>
<vue-html2pdf
:show-layout="true"
:float-layout="false"
:enable-download="true"
:preview-modal="true"
filename="document"
:paginate-elements-by-height="1400"
pdf-content-width="800px"
pdf-orientation="portrait"
pdf-format="a4"
ref="html2Pdf"
>
<template v-slot:pdf-content>
<!-- PDF内容 -->
</template>
</vue-html2pdf>
<button @click="generatePDF">生成PDF</button>
</div>
</template>
<script>
import VueHtml2pdf from 'vue-html2pdf'
export default {
components: {
VueHtml2pdf
},
methods: {
generatePDF() {
this.$refs.html2Pdf.generatePdf()
}
}
}
</script>
使用浏览器打印API实现打印功能
创建打印方法
export const printElement = (element) => {
const printWindow = window.open('', '_blank')
printWindow.document.write('<html><head><title>打印</title></head><body>')
printWindow.document.write(element.innerHTML)
printWindow.document.write('</body></html>')
printWindow.document.close()
printWindow.focus()
setTimeout(() => {
printWindow.print()
printWindow.close()
}, 500)
}
在Vue组件中使用
<template>
<div ref="printContent">
<!-- 需要打印的内容 -->
</div>
<button @click="print">打印</button>
</template>
<script>
import { printElement } from './printUtils'
export default {
methods: {
print() {
printElement(this.$refs.printContent)
}
}
}
</script>
使用CSS媒体查询优化打印样式
添加打印样式
@media print {
body * {
visibility: hidden;
}
.print-content, .print-content * {
visibility: visible;
}
.print-content {
position: absolute;
left: 0;
top: 0;
width: 100%;
}
.no-print {
display: none !important;
}
}
注意事项
PDF生成质量取决于HTML内容的复杂度,复杂布局可能需要额外调整
图片需要完全加载后才能正确转换为PDF,建议添加加载状态处理
打印功能可能受浏览器安全策略限制,某些内容可能无法打印
对于大量数据分页处理,需要计算合适的分页高度参数

考虑添加加载指示器和错误处理机制提升用户体验





