我做PDF列印功能是在前端用Vue3实现的,具体是使用pdfme生成PDF模版并往模版中填充数据。适用于排
版格式固定的PDF(下载资源为引入的字体)。
pdfme的官网地址:https://pdfme.com/
安装套件
npm i @pdfme/generator @pdfme/common
npm i @pdfme/ui @pdfme/common
<button class="bg-blue-600 text-white h-9 w-28" @click="exportPDF()">导出PDF</button>
<script lang="ts" setup>
import type { Template, Font } from '@pdfme/common'
import { generate } from '@pdfme/generator'
let font: Font
//pdfme官方文档中只支持英文书写中文会乱码,所以需要自己引入中文字体
//我引入的字体是繁体中文(简体会乱码,可以自己找需要的字体引入,引入的字体格式必须为.ttf格式)
fetch('src/assets/fonts/NotoSansTC-VariableFont_wght.ttf').then((res) => {
res.arrayBuffer().then(buffer => {
font = {
Roboto_Regular: {
data: buffer,
fallback: true
}
}
})
})
let base64: any
//官方文档中basePdf为base64格式的篇幅太长,所以我把模版直接放在了账目中转为base64格式
fetch('src/assets/pdf/document.pdf')
.then((response) => response.blob())
.then((res) => {
const blob = new Blob([res], { type: 'application/pdf' })
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = () => {
base64 = reader.result
resolve(base64)
}
reader.onerror = error => reject(error)
})
})
const exportPDF = () => {
//schemas为填充内容框架(包括位置、类型、字体、颜色等信息);
//basePdf为基础模版信息
//inputs填充的内容
(async() => {
const template :Template = {
schemas: [
{
name: {
type: 'text',
position: {
x: 25.4,
y: 26.19
},
width: 76.01,
height: 14.94,
fontSize: 20,
fontName: 'Roboto_Regular',
fontColor: '#ff0000'
}
}
],
basePdf: base64
}
const inputs = [
{
name: '看這裡,我用的是繁體語言包,簡體可能會亂碼'
}
]
const pdf = await generate({ template, inputs, options: { font } })
const blob = new Blob([pdf.buffer], { type: 'application/pdf' })
window.open(URL.createObjectURL(blob))
})()
}
</script>
显示效果: