vue导出含echarts的html | PDF

3,149

要导出的vue组件如下:

<div id="id" ref="resume">
    <button @click="downloadHtml('报告')">html</button>
    <button @click="getPdf('id',报告')">pdf</button>
    <situation></situation>
</div>

1、vue导出.html文件

HTML页面由.css、htmlDom标签组成,将css设置成js通过export导出,htmlDom可以通过$el.innerHTML获得,也可通过document.getElementById('id')获得 。然后构造html页面,使用createObjectURL创建一个文件流下载。代码如下:

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' 包,也可以写原生代码。如下:

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.js

export const resumecss = `
  html,body{
    padding: 0;
    margin: 0;
  }
  ...
`

如果导出的页面含echarts, 需要在 series 中设置 animation: false, 作用是关闭动画。

导出echarts一般是将其转成图片,使用图片展示。

this.url = this.chart.getDataURL({
    pixelRatio: 2,
    backgroundColor: '#192636'
});

我之前一直有一个思想误区,就是点击下载的时候给子组件传值,让其图片显示echarts隐藏,后来发现完全没必要,只需加一个class,在download.css.js控制显隐,简单粗暴。

2、导出PDF

创建htmlToPdf.js页面

// 导出页面为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', '报告') 即可。