vue html pdf,Vue-html2pdf Html 生成 pdf 【踩坑实记】

1. 背景

前端直接根据 html 生成 pdf, 减轻后端压力

3. 坑点

**打印位置偏移hack 滚动条 X Y 轴 打印前需要置零**

handleDownloadPDF() {

let scrollTop = document.documentElement.scrollTop

let scrollLeft = document.documentElement.scrollLeft

this.tableOptions.loading = true

API

.xxxxx()

.then((res) => {

document.documentElement.scrollTop = 0

document.documentElement.scrollLeft = 0

this.$refs.html2Pdf.generatePdf()

})

.finally(() => {

document.documentElement.scrollTop = scrollTop

document.documentElement.scrollLeft = scrollLeft

this.tableOptions.loading = false

})

},

分页 --  通过 css 控制分页位置

.page-break-after {

page-break-after: always;

}

打印宽度 pdf-content-width="'98%'"

v-show="!printState"

ref="html2Pdf"

:enable-download="true"

:filename="fileName"

:float-layout="false"

:html-to-pdf-options="pdfOptions"

:manual-pagination="true"

:paginate-elements-by-height="1400"

:pdf-content-width="'98%'"

:pdf-quality="2"

:preview-modal="false"

:show-layout="false"

pdf-format="a4"

pdf-orientation="landscape"

>

computed: {

fileName() {

return `xxxx`

},

pdfOptions() {

return {

margin: [0, 5, 0, 5],

filename: this.fileName

}

},

},

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 中使用 pdf-lib 和 html2canvas 生成 PDF 文件需要进行以下几个步骤: 1. 安装依赖库 在项目中使用 npm 或者 yarn 安装 pdf-lib 和 html2canvas 依赖库。 2. 引入依赖库 在需要使用的 Vue 组件中引入 pdf-lib 和 html2canvas 依赖库。 ```javascript import { PDFDocument, StandardFonts } from 'pdf-lib'; import html2canvas from 'html2canvas'; ``` 3. 创建 PDF 文档对象 使用 pdf-lib 库中的 PDFDocument 类来创建 PDF 文档对象,并添加需要生成 PDF 的内容。 ```javascript const pdfDoc = await PDFDocument.create(); const page = pdfDoc.addPage([595.28, 841.89]); // 设置页面大小 const font = await pdfDoc.embedFont(StandardFonts.HelveticaBold); // 在页面上添加文本内容 page.drawText('Hello, PDF!', { x: 50, y: 700, size: 24, font: font, color: rgb(0, 0, 0), }); ``` 4. 将 HTML 元素转换为 Canvas 使用 html2canvas 库中的 toCanvas 方法将需要生成 PDFHTML 元素转换为 Canvas 对象。 ```javascript const canvas = await html2canvas(document.getElementById('pdf-content')); ``` 5. 将 Canvas 对象转换为 PNG 图片 将上一步得到的 Canvas 对象转换为 PNG 格式的图片。 ```javascript const pngUrl = canvas.toDataURL('image/png'); ``` 6. 添加 PNG 图片到 PDF 文档中 将上一步得到的 PNG 图片添加到 PDF 文档对象中。 ```javascript const pngImage = await pdfDoc.embedPng(pngUrl); page.drawImage(pngImage, { x: 50, y: 450, width: 500, height: 250, }); ``` 7. 导出 PDF 文件 使用 pdf-lib 库中的 save 方法将生成PDF 文件导出。 ```javascript const pdfBytes = await pdfDoc.save(); const blob = new Blob([pdfBytes], { type: 'application/pdf' }); saveAs(blob, 'example.pdf'); // 将 PDF 文件保存到本地 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值