要导出的vue组件以下:css
<div id="id" ref="resume">
<button @click="downloadHtml('报告')">html</button>
<button @click="getPdf('id',报告')">pdf</button>
<situation></situation>
</div>
复制代码
一、vue导出.html文件html
HTML页面由.css、htmlDom标签组成,将css设置成js经过export导出,htmlDom能够经过$el.innerHTML得到,也可经过document.getElementById('id')得到 。而后构造html页面,使用createObjectURL建立一个文件流下载。代码以下:vue
import {resumecss} from '@/styles/download.css.js'
import writer from 'file-writer'
methods:{
download(name){
let html = this.getHtml();
let s = writer(`${name}.html`, html, 'utf-8');
},
getHtml(){
const template = this.$refs.resume.innerHTML
let html = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>html</title>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<style> ${resumecss} </style>
</head>
<body>
<div style="margin:0 auto;width:1200px">
${template}
</div>
</body>
</html>`
return html
},
}
复制代码
安装 'file-writer' 包,也能够写原生代码。以下:npm
1> 安装 'file-writer' 包: npm install -D file-writer
2> 原生代码:
function writer(fileName,content,option){
var a = document.createElement('a');
var url = window.URL.createObjectURL(new Blob([content],
{ type: (option.type || "text/plain") + ";charset=" + (option.encoding || 'utf-8') }));
a.href = url;
a.download = fileName || 'file';
a.click();
window.URL.revokeObjectURL(url);
}
复制代码
download.css.jselement-ui
export const resumecss = `
html,body{
padding: 0;
margin: 0;
}
...
`
复制代码
若是导出的页面含echarts, 须要在 series 中设置 animation: false, 做用是关闭动画。canvas
导出echarts通常是将其转成图片,使用图片展现。echarts
this.url = this.chart.getDataURL({
pixelRatio: 2,
backgroundColor: '#192636'
});
复制代码
我以前一直有一个思想误区,就是点击下载的时候给子组件传值,让其图片显示echarts隐藏,后来发现彻底不必,只需加一个class,在download.css.js控制显隐,简单粗暴。jsp
二、导出PDF动画
建立htmlToPdf.js页面ui
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default{
install (Vue, options) {
Vue.prototype.getPdf = function (id,title) {
html2Canvas(document.querySelector(`#${id}`), {
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 = 595.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', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(title + '.pdf')
}
)
}
}
}
复制代码
在main.js中引入
import htmlToPdf from '@/components/utils/htmlToPdf'
Vue.use(htmlToPdf)
复制代码
下载PDF只需使用 getPdf('id', '报告') 便可。