Vue使用jspdf导出页面为PDF格式
安装两个依赖将页面html转换成图片cnpm install --save html2canvas将图片生成pdfcnpm install jspdf --save把htmlToPdf.js(在上传中心可以找到我上传的这个js)放到文件夹中,这里放到的是“src\components\base”在main.js里引用import htmlToPdf from './compon...
·
参考了别人的文章,整合一下,写了这篇笔记
安装两个依赖
将页面html转换成图片
cnpm install --save html2canvas
将图片生成pdf
cnpm install jspdf --save
把htmlToPdf.js(在上传中心可以找到我上传的这个js)放到文件夹中,这里放到的是“src\components\base”
在main.js里引用
import htmlToPdf from './components/base/htmlToPdf.js'
Vue.use(htmlToPdf)
页面代码
<template>
<div class="a4Page">
<button class="btn btn-primary" @click="getPdf()">生成PDF</button>
</div>
<div id="printPage">
<br>内容
</div>
</template>
<script>
import restHelper from '../service/RestApiHelper.js'
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
methods:{
getPdf:function(){
var title = “导出名称”;
html2Canvas(document.querySelector('#printPage'), {
// allowTaint: true
useCORS:true//看情况选用上面还是下面的,
}).then(function (canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 575.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 10, 10, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 10, position, imgWidth, imgHeight)//这里的10是左右边距
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(title + '.pdf')
})
},
}
}
如果生成的pdf较模糊,可以将canvas的属性width和height属性放大为2倍,再将canvas的css样式width和height设置为原来1倍的大小即可,也就是,先将canvas高分辨率输出,再来压缩导出打印,修改getPdf的方法为如下,
getPdf:function(){
var title = this.htmlTitle+this.contract.contractNO;
var dom=document.getElementById('#printPage')
var c = document.createElement("canvas")
var opts = {
scale: 2,
canvas: c,
logging: true,
width: document.querySelector('#printPage').width,
height: document.querySelector('#printPage').height
};
c.width = document.querySelector('#printPage').width * 2
c.height = document.querySelector('#printPage').height * 2
c.getContext("2d").scale(2, 2);
html2Canvas(document.querySelector('#printPage'), opts).then(function (canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 575.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 10, 10, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 10, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(title + '.pdf')
})
}
},
更多推荐
已为社区贡献3条内容
所有评论(0)