当前位置:首页 > VUE

vue实现pdf下载

2026-02-11 06:38:41VUE

Vue 中实现 PDF 下载的方法

使用前端库生成 PDF

安装 html2pdf.jsjspdf 库,将 HTML 内容转换为 PDF 并下载。

npm install html2pdf.js

在 Vue 组件中引入并使用:

import html2pdf from 'html2pdf.js';

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

从服务器下载 PDF

vue实现pdf下载

通过 API 请求获取 PDF 文件流,使用 BlobURL.createObjectURL 实现下载。

downloadPDF() {
  axios.get('/api/pdf', { responseType: 'blob' })
    .then(response => {
      const blob = new Blob([response.data], { type: 'application/pdf' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'document.pdf';
      link.click();
      URL.revokeObjectURL(link.href);
    });
}

直接链接下载

若 PDF 文件已存储在服务器,可通过 <a> 标签直接下载。

vue实现pdf下载

<a href="/path/to/document.pdf" download>Download PDF</a>

动态生成 PDF 内容

使用 jspdf 动态创建 PDF 内容:

import jsPDF from 'jspdf';

generatePDF() {
  const doc = new jsPDF();
  doc.text('Hello World!', 10, 10);
  doc.save('document.pdf');
}

注意事项

  • 跨域问题需确保服务器配置正确的 CORS 头。
  • 大文件下载建议分块或显示进度条。
  • 移动端部分浏览器可能限制自动下载,需用户手动触发。

标签: vuepdf
分享给朋友:

相关文章

vue实现tablegrid

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue列表实现

vue列表实现

Vue 列表实现方法 使用 v-for 指令 v-for 是 Vue 中用于渲染列表的核心指令,基于数据源动态生成 DOM 元素。语法格式为 item in items 或 (item, index)…

vue router 实现

vue router 实现

Vue Router 的实现 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是 Vue Router 的核心实现方式。 安装 Vue Router 通过…

vue实现route

vue实现route

Vue 路由实现方法 Vue 中实现路由通常使用 vue-router 库,这是 Vue 官方推荐的路由管理器。以下是具体实现步骤: 安装 vue-router 通过 npm 或 yarn 安装…

vue实现换肤

vue实现换肤

使用 CSS 变量实现换肤 在 Vue 项目中,可以通过 CSS 变量(Custom Properties)动态切换主题色。CSS 变量可以在运行时修改,适合实现换肤功能。 定义全局 CSS 变量:…

vue实现前端

vue实现前端

Vue 实现前端的核心方法与步骤 安装 Vue 项目 使用 Vue CLI 或 Vite 创建项目。Vue CLI 是传统构建工具,Vite 是新一代轻量级工具。 npm init vue@la…