要導出的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', '報告') 便可。