当前位置:首页 > VUE

vue 实现导出pdf

2026-03-28 11:12:04VUE

Vue 实现导出 PDF 的方法

使用 html2pdf.js 库

安装 html2pdf.js:

npm install html2pdf.js

在 Vue 组件中引入并使用:

import html2pdf from 'html2pdf.js';

export default {
  methods: {
    exportToPDF() {
      const element = document.getElementById('content-to-export');
      const opt = {
        margin: 1,
        filename: 'document.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2 },
        jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
      };
      html2pdf().from(element).set(opt).save();
    }
  }
}

使用 jsPDF 和 html2canvas

安装依赖:

npm install jspdf html2canvas

在 Vue 组件中实现:

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

export default {
  methods: {
    async exportToPDF() {
      const element = document.getElementById('content-to-export');
      const canvas = await html2canvas(element);
      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF('p', 'mm', 'a4');
      const imgWidth = 210;
      const imgHeight = canvas.height * imgWidth / canvas.width;
      pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
      pdf.save('document.pdf');
    }
  }
}

使用 vue-html2pdf 插件

安装插件:

npm install vue-html2pdf

在 Vue 组件中使用:

import VueHtml2pdf from 'vue-html2pdf';

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

模板部分:

<vue-html2pdf
  ref="html2Pdf"
  :filename="filename"
  :pdf-quality="2"
  :enable-download="true"
>
  <div slot="pdf-content">
    <!-- 要导出的内容 -->
  </div>
</vue-html2pdf>
<button @click="generateReport">导出 PDF</button>

注意事项

  • 确保导出的内容在 DOM 中可见
  • 对于复杂布局,可能需要调整 html2canvas 的 scale 参数
  • 中文支持可能需要引入额外的字体
  • 大文档导出可能需要优化性能

中文支持方案

对于需要支持中文的情况,可以在 jsPDF 中加载中文字体:

const pdf = new jsPDF();
pdf.addFileToVFS('NotoSansSC-Regular.ttf', fontData);
pdf.addFont('NotoSansSC-Regular.ttf', 'NotoSansSC', 'normal');
pdf.setFont('NotoSansSC');

服务器端生成方案

对于更复杂的 PDF 生成需求,可以考虑:

vue 实现导出pdf

  • 使用 Puppeteer 在服务器端生成
  • 调用专业的 PDF 生成 API
  • 使用 PDFKit 等库进行编程式生成

标签: vuepdf
分享给朋友:

相关文章

vue实现按卡片轮播

vue实现按卡片轮播

实现卡片轮播的基本思路 在Vue中实现卡片轮播可以通过结合v-for指令和动态样式绑定完成。核心是维护一个当前显示卡片的索引,通过CSS过渡效果实现平滑切换。 基础实现步骤 模板部分 使用v-for…

vue 实现权限

vue 实现权限

Vue 实现权限控制的方法 在 Vue 项目中实现权限控制通常涉及前端路由、组件和按钮级别的权限管理。以下是几种常见的实现方式: 路由权限控制 通过路由守卫实现权限验证,过滤用户无权访问的路由:…

vue实现过程

vue实现过程

Vue 的实现过程 Vue 的实现过程可以分为多个核心模块,包括响应式系统、虚拟 DOM、模板编译等。以下是 Vue 的主要实现过程分析。 响应式系统 Vue 的响应式系统基于 Object.def…

实现vue table

实现vue table

Vue 表格实现方法 基础表格实现 使用 Vue 的 v-for 指令可以快速渲染表格数据。在模板中定义表格结构,通过数据绑定动态生成行和列。 <template> <tabl…

vue实现swiper

vue实现swiper

Vue 中实现 Swiper 的方法 安装 Swiper 依赖 在 Vue 项目中安装 Swiper 和相关依赖: npm install swiper vue-awesome-swiper 全局引…

vue日历实现

vue日历实现

实现基础日历布局 使用Vue的模板语法构建日历的基本HTML结构。一个典型的日历包含星期标题和日期格子,可以通过v-for循环生成。月份切换功能通过计算属性动态更新日期数组。 <templat…