在 Vue 中使用 ECharts 进行打印时,可以通过 ECharts 提供的 getDataURL 方法获取图表的 Base64 图片 URL,然后使用浏览器的打印 API 进行打印。以下是一个简单的示例:

  1. 首先,确保你已经在 Vue 项目中安装并配置了 ECharts

  2. 在你的 Vue 组件中,创建一个方法来处理打印逻辑.

<template>
  <div>
    <v-chart :options="chartOptions" ref="echart" />
    <button @click="printChart">打印图表</button>
  </div>
</template>
 
<script>
import ECharts from 'vue-echarts';
 
export default {
  components: {
    'v-chart': ECharts
  },
  data() {
    return {
      chartOptions: {
        // ECharts 配置项
      }
    };
  },
  methods: {
    printChart() {
      const chart = this.$refs.echart.echart; // 获取 ECharts 实例
      const imgUrl = chart.getDataURL({
        // 导出图表的格式、质量和尺寸
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff',
        excludeComponents: ['toolbox']
      });
 
      // 创建一个临时的 iframe 用于打印
      const iframe = document.createElement('iframe');
      iframe.style.visibility = 'hidden';
      iframe.style.height = '0px';
      iframe.style.width = '0px';
      document.body.appendChild(iframe);
 
      // 等 iframe 加载完成后打印
      iframe.onload = function() {
        const contentWindow = iframe.contentWindow;
        const document = contentWindow.document;
        document.open();
        document.write('<img src="' + imgUrl + '" />'); // 将图表的 Base64 图片插入 iframe
        document.close();
        contentWindow.focus();
        contentWindow.print(); // 执行打印命令
        document.body.removeChild(iframe); // 打印后移除 iframe
      };
 
      iframe.src = 'about:blank'; // 触发 iframe 的加载
    }
  }
};
</script>

在上述代码中, printChart 方法首先通过 ECharts 实例的 getDataURL 方法获取图表的 Base64 图片 URL。然后,它创建一个隐藏的 iframe ,将图表的 Base64 图片 URL 作为一个 img 标签插入到 iframe 中,并触发打印命令。打印完成后, iframe 会被移除。这样就可以实现在 Vue 中使用 ECharts 并打印图表的功能。