赞
踩
问题:最近项目有个需求,将前端页面生成PDF
解决方法:
1、首先生成报告页面,也就是常规页面
2、然后将页面转换成图片 (用到的组件html2cabvas)
3、最后将图片导出成PDF (用到的组件 jspdf )
具体步骤:
1、安装依赖
npm install --save html2canvas // 页面转图片
npm install jspdf --save // 图片转pdf
2、在你想要生成pdf的元素上添加一个id,如下所示我添加了一个 id = pdfDom
3、在项目公共方法中创建i个生成pdf的方法,如在目录utils下创建一个pdf.js
4、然后就是写一个生成pdf的方法
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
install(Vue, options) {
Vue.prototype.getPdf = function (dom,reportName,isDownload=true) {
return new Promise((resolve,reject)=>{
html2Canvas(document.querySelector(`#${id}`), {
allowTaint: true,
taintTest: false,
useCORS: true,
dpi: window.devicePixelRatio * 1, // 将分辨率提高到特定的DPI 提高四倍
scale: 2, // 按比例增加分辨率
logging: true // 可以长屏分页导出
}).then(function (canvas) {
const PDF = new JSPDF('p','mm','a4')
const ctx = canvas.getContext('2d')
const a4w = 170
const a4h = 267
const imgHeight = Math.floor(a4h*canvas.width/a4w)
let renderHeight = 0
while(renderHeight<canvas.height){
const page = document.createElement('canvas')
page.width = canvas.width
page.height = Math.min(imgHeight,canvas.height-renderHeight)
page.getContext('2d').putImageData(ctx.getImageData(0,renderHeight,canvas.width,Math.width,Math.min(imgHeight,canvas.height-renderHeight)),0,0)
renderHeight += imgHeight
if(renderHeight<canvas.height){
PDF.addPage()
}
}
if(isDownload){
PDF.save(title+'.pdf')
}
var pdfData = PDF.output('datauristring')
resolve(pdfData)
})
})
}
}
}
函数入参:
dom:想要生成pdf的元素
reportName:生成pdf的标题
isDownload:是否直接下载
5、创建完pdf后我们需要在main.js中引入并注册
import HtmlToPdf from '@/utils/pdf.js'
Vue.use(HtmlToPdf)
6、注册完之后就可以直接使用了,回到想要生成pdf的页面,如点击提交按钮需要生成pdf,我们就可以在提交方法中调用getpdf这个方法
this.getPdf(document.querySelect('#pdfDom'),title,false).then(
(res) => {
console.log('生成pdf成功')
}
)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。