Vue3中PDF列印功能(pdfme)

    我做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>

显示效果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值