vue实现pdf打印开单
Vue 实现 PDF 打印开单的方法
使用 html2pdf.js 库
安装 html2pdf.js 库:
npm install html2pdf.js
在 Vue 组件中引入并使用:
import html2pdf from 'html2pdf.js'
export default {
methods: {
generatePDF() {
const element = document.getElementById('pdf-content')
const opt = {
margin: 10,
filename: 'invoice.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
}
html2pdf().from(element).set(opt).save()
}
}
}
使用 jsPDF 和 html2canvas
安装依赖:
npm install jspdf html2canvas
实现代码:
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'
export default {
methods: {
async downloadPDF() {
const doc = new jsPDF()
const element = document.getElementById('pdf-content')
const canvas = await html2canvas(element)
const imgData = canvas.toDataURL('image/png')
doc.addImage(imgData, 'PNG', 10, 10, 190, 0)
doc.save('invoice.pdf')
}
}
}
使用 Vue 模板设计打印内容
在模板中设计打印区域:
<template>
<div>
<div id="pdf-content">
<!-- 这里放置需要打印的内容 -->
<h1>发票</h1>
<table>
<tr>
<th>项目</th>
<th>数量</th>
<th>单价</th>
</tr>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.quantity }}</td>
<td>{{ item.price }}</td>
</tr>
</table>
</div>
<button @click="generatePDF">打印PDF</button>
</div>
</template>
样式优化
为打印内容添加专门样式:
@media print {
body * {
visibility: hidden;
}
#pdf-content, #pdf-content * {
visibility: visible;
}
#pdf-content {
position: absolute;
left: 0;
top: 0;
}
}
使用打印专用CSS
创建打印专用样式表:
.print-only {
display: none;
}
@media print {
.no-print {
display: none;
}
.print-only {
display: block;
}
}
服务端生成PDF
如果需要更复杂的PDF生成,可以考虑使用服务端方案:
- 使用Node.js的pdfkit或puppeteer
- 通过API将HTML发送到后端生成PDF
- 前端下载生成的PDF文件
注意事项
- 确保打印内容宽度不超过A4纸尺寸(210mm)
- 测试不同浏览器的兼容性
- 考虑添加加载状态,因为生成PDF可能需要时间
- 对于复杂表格,可能需要调整html2canvas的缩放比例







