是否可以使用 vue-chartjs 打印图表?

Is it possible to print a chart with vue-chartjs?

我正在使用 vue-chartjs 在 Web 应用程序上呈现图表。我知道如果您使用的是原始 library,您可以打印图表。但是我不知道如何使用库的 vue 版本。

我在外部 charts.js 文件中有我的图表变量

import {Bar, mixins } from 'vue-chartjs'
Chart.defaults.global
let chartOptions = Chart.defaults.global;   
const { reactiveProp } = mixins
export default {
   extends: Bar,
   mixins: [reactiveProp],
   props: ['options'],

   mounted () {
    let that = this;
    that.chartOptions = {
      scales: {
        yAxes: [{
            ticks: {
                suggestedMin: 0,  
                fontFamily: "'Overpass_Mono', 'Monaco', monospace",
                fontColor: "rgba(254, 255, 248, 0.5)"
            },
            gridLines: {
                color: 'rgba(255, 80, 248, 0.08)',
                zeroLineColor: 'rgb(168, 119, 181)',
                 zeroLineWidth: 2
            },
        }],
        xAxes: [{
            ticks: {
                suggestedMin: 0,    
                 fontColor: "rgb(168, 119, 181)"

            },
            gridLines: {
                color: 'rgba(255, 80, 248, 0.08)',
                zeroLineColor: 'transparent',
            }
        }],
    },
    legend: {
        labels: {
            fontColor: 'rgb(168, 119, 181)',
        }
    }
  },
    this.renderChart(this.chartData, that.chartOptions)
  }
}

然后在我的组件模板上有:

<template>
    <div class="report">
        <charts v-if="todaySelected"
                :chart-id="'total_visits_chart_bar'" 
                :height="chartsHeight" 
                :options="chartOptions"
                :chart-data="datacollection" 
        ></charts>
        <div v-if="todaySelected">
        <button @click="printChart(charts)">Print chart</button>
    </div>
</template>
<script>
import charts from './chart_0.js'
    components: {
       charts,
    },
    data() {
        return{
             datacollection: {"datasets":[{"label":"Entries Today","data":[15,15,15,0]},{"label":"Currently Inside","data":[2,2,2,0]}],"labels":[]}
        }
     }.
 methods: {
     printChart(charts) {
        charts.print();
     },
  }
</script>

如有任何帮助,我们将不胜感激。

该库似乎是基于 chartjs 而不是 canvasjs https://www.chartjs.org/docs/latest/ you might want to look into how to print a window Quick Print HTML5 Canvas,请记住您可以访问绘制图形的 canvas 元素:

 methods: {
     printChart() {
        const canvasEle = this.$el.querySelector('canvas');
        //now your chart image is on canvasEle 
     },
  }

答案是:是的。组件脚本中的打印方法可以是:

methods:{
  printChart() {
    var canvasEle = document.getElementById('total_visits_chart_bar');
    var win = window.open('', 'Print', 'height=600,width=800');
    win.document.write("<br><img src='" + canvasEle.toDataURL() + "' />");
    setTimeout(function(){ //giving it 200 milliseconds time to load
            win.document.close();
            win.focus()
            win.print();
            win.location.reload()
    }, 200);  
  },
}

您还可以将其添加到组件的样式中:

@media print{
    @page {
        size: landscape
        }
}

vue-chartjs 基于 chart.js 而不是 canvas.js,因此它没有 "build-in" 打印方式。

您必须使用一些自定义逻辑和本机 javascript 打印功能来完成。

然而,您可以在图表组件中获取 canvas 元素并生成例如图像,然后打印该图像。

这会有点棘手,因为您只能访问图表组件内的 canvas。因此,您可能需要等待一个事件或道具来触发 toDataURL 调用,然后将图像发送到您可以打印它的父组件。如果你想在你的父组件中触发打印。

methods: {
   print () {
     // grab the canvas and generate an image
     let image = this.$refs.canvas.toDataURL('image/png')
     // Emits an event with the image
     this.$emit('chart:print', image)
   }
}

在你的父组件中:

<template>
 <your-chart @chart:print="handlePrint"
<template/>

....
...

methods: {
 handlePrint(image) {
   const win = window.open('', 'Print', 'height=600, width=800')
   win.document.write(`<br><img src='${image}' />`)
   win.print()
   win.close()
 }
}

如果您不反对使用导出为pdf格式,您可以使用jsPDF库实现这个任务,例如:

<template>
    <div class="report">
        <charts v-if="todaySelected"
                :chart-id="'total_visits_chart_bar'" 
                :height="chartsHeight" 
                :options="chartOptions"
                :chart-data="datacollection" 
        ></charts>
    </div>
</template>
<script>
import jsPDF from 'jspdf'; //for PDF printing
methods: {
  pdfThatThing : function(){
      //Default export is a4 paper, portrait, using milimeters for units      
      let pdfName = 'test'; 
      var doc = new jsPDF();
      doc.text("Header", 20, 20); //at x,y at def.units 2cm
      //chart element
      let canvasEle = document.getElementById('total_visits_chart_bar');
      let chartURL = canvasEle.toDataURL(); //transform path 
      //a4 page is 209mm, adds at 4cm top, 2cm left, for 15cm in size      
      doc.addImage(chartURL, 'PNG', 20, 40, 150, 150 )
      doc.save(pdfName + '.pdf');
    },
}
</script>

还有一个选项可以在 pdf 查看器中自动显示打印对话框:

doc.autoPrint({variant: 'non-conform'})