当前位置:首页 > VUE

vue实现导出PDF

2026-02-19 04:52:40VUE

实现Vue导出PDF的方法

使用html2canvas和jspdf库

安装依赖库:

npm install html2canvas jspdf --save

在Vue组件中引入:

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

创建导出方法:

methods: {
  exportToPDF() {
    const element = document.getElementById('pdf-content');
    html2canvas(element).then(canvas => {
      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF('p', 'mm', 'a4');
      const imgWidth = 210;
      const pageHeight = 295;
      const imgHeight = canvas.height * imgWidth / canvas.width;
      let heightLeft = imgHeight;
      let position = 0;

      pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;

      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        pdf.addPage();
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }

      pdf.save('document.pdf');
    });
  }
}

使用vue-html2pdf插件

安装插件:

npm install vue-html2pdf --save

在组件中使用:

vue实现导出PDF

import VueHtml2pdf from 'vue-html2pdf'

export default {
  components: {
    VueHtml2pdf
  },
  methods: {
    generateReport() {
      this.$refs.html2Pdf.generatePdf()
    }
  }
}

模板部分:

<vue-html2pdf
  ref="html2Pdf"
  :html-to-pdf-options="options"
  filename="my-pdf"
  :paginate-x="156"
  :paginate-y="180"
>
  <div slot="pdf-content">
    <!-- 要导出的内容 -->
  </div>
</vue-html2pdf>
<button @click="generateReport">导出PDF</button>

使用pdfmake客户端生成

安装pdfmake:

npm install pdfmake --save

实现代码:

vue实现导出PDF

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

methods: {
  generatePDF() {
    const docDefinition = {
      content: [
        { text: 'PDF标题', style: 'header' },
        '这是PDF内容...',
        { text: '动态内容', margin: [0, 20, 0, 0] }
      ],
      styles: {
        header: {
          fontSize: 18,
          bold: true
        }
      }
    };
    pdfMake.createPdf(docDefinition).download('custom.pdf');
  }
}

注意事项

确保要导出的内容已完全渲染,可在mounted钩子或使用$nextTick处理异步渲染问题

对于大量数据或复杂布局,考虑分页处理避免PDF文件过大

中文支持需要额外配置字体,pdfmake需要注册中文字体

浏览器安全策略可能限制跨域资源导出,确保所有资源同源或已正确处理CORS

标签: vuePDF
分享给朋友:

相关文章

vue tag实现

vue tag实现

Vue 标签实现方法 在 Vue 中实现标签功能可以通过多种方式完成,常见场景包括动态标签生成、标签输入框、标签管理等。以下是几种典型实现方案: 动态标签列表渲染 使用 v-for 指令渲染标签数组…

vue 实现脚本

vue 实现脚本

Vue 实现脚本的方法 Vue.js 提供了多种方式来实现脚本功能,包括组件内脚本、混入(Mixins)、插件(Plugins)以及自定义指令等。以下是常见的实现方式: 组件内脚本 在 Vue 单文…

vue轮播实现

vue轮播实现

Vue 轮播实现方法 使用第三方库(推荐) 安装 swiper 或 vue-awesome-swiper 库,快速实现功能丰富的轮播效果。 以 vue-awesome-swiper 为例: npm…

vue实现折叠

vue实现折叠

Vue 实现折叠功能 在 Vue 中实现折叠功能可以通过多种方式完成,以下介绍几种常见的方法。 使用 v-show 或 v-if 控制显示隐藏 通过 Vue 的指令 v-show 或 v-if 可以…

vue实现绘图

vue实现绘图

Vue 实现绘图的方法 在 Vue 中实现绘图功能,可以通过多种方式实现,包括使用原生 HTML5 Canvas、第三方库(如 Fabric.js、Konva.js)或 SVG。以下是几种常见的实现方…

vue如何实现登录

vue如何实现登录

实现登录功能的基本步骤 使用Vue实现登录功能通常需要结合后端API、状态管理以及路由控制。以下是常见的实现方式: 创建登录表单组件 在Vue组件中构建包含用户名和密码输入框的表单: <te…