vue2使用pdfjs-dist和jsPDF生成pdf文件
1、安装依赖
powershell
npm install pdfjs-dist@2.6.347
2、引入依赖
javascript
import { jsPDF } from 'jspdf'
javascript
// 使用require方式导入pdfjs-dist v2.5.207,高版本报错(import导入会报错:GlobalWorkerOptions undefined)
this.pdfjsLib = require('pdfjs-dist/build/pdf')
this.pdfjsLib.GlobalWorkerOptions.workerSrc = './pdf.worker.js'// 将pdfjs-dist/build/pdf.worker.js文件复制到public下
3、使用
javascript
/**
* 使用pdfjs-dist将每一页pdf转为图片(canvas->图片数据url)
* 使用jspdf将图片合并为新的pdf(pdf-lib不支持图片直接转为pdf页面)
*/
const pdfDoc = await this.pdfjsLib.getDocument(pdfBytes).promise
const outputPdf = new jsPDF(true)
let i = 1
for (i = 1; i <= pdfDoc.numPages; i++) {
const page = await pdfDoc.getPage(i)
const viewport = page.getViewport({ scale: 1.9 })
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
canvas.width = viewport.width
canvas.height = viewport.height
// Render PDF page into canvas
await page.render({ canvasContext: context, viewport }).promise
// Add canvas as image to PDF
const imgData = canvas.toDataURL('image/png')
if (i > 1) {
outputPdf.addPage()
}
outputPdf.addImage(imgData, 'PNG', 0, 0, 210, 297, undefined, 'FAST') // A4 size
canvas.remove() // Clean up
}
// Save the new PDF
const pdfblob = outputPdf.output('blob')
const url = window.URL.createObjectURL(pdfblob)
// 下载到本地
// const url = window.URL.createObjectURL(new Blob([mergedPdfFile.buffer]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'test.pdf')
document.body.appendChild(link)
link.click()
4、注意
1)pdfjs-dist安装低版本,高版本报错
2)如需压缩图片
new jsPDF(true)
outputPdf.addImage(imgData, 'PNG', 0, 0, 210, 297, undefined, 'FAST')
3)如果将多个图像添加到一个文档中,请使用
javascript
outputPdf.addImage(imgData, 'PNG', 0, 0, 210, 297, undefined, 'FAST')
而不是
javascript
outputPdf.addImage(imgData, 'PNG', 0, 0, 210, 297, '', 'FAST')
否则第一张图片将替换所有其他图片