当前位置:首页 > VUE

vue实现pdf浏览

2026-01-17 13:00:41VUE

Vue 中实现 PDF 浏览的方法

使用 pdf.js

pdf.js 是 Mozilla 开发的开源库,可直接在浏览器中渲染 PDF 文件。安装依赖:

npm install pdfjs-dist

示例代码:

<template>
  <div>
    <canvas ref="pdfCanvas"></canvas>
  </div>
</template>

<script>
import * as pdfjsLib from 'pdfjs-dist';

export default {
  props: {
    pdfUrl: String,
  },
  mounted() {
    this.loadPdf();
  },
  methods: {
    async loadPdf() {
      const loadingTask = pdfjsLib.getDocument(this.pdfUrl);
      const pdf = await loadingTask.promise;
      const page = await pdf.getPage(1);
      const viewport = page.getViewport({ scale: 1.0 });
      const canvas = this.$refs.pdfCanvas;
      const context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      await page.render({
        canvasContext: context,
        viewport: viewport,
      }).promise;
    },
  },
};
</script>

使用 vue-pdf 插件

vue-pdf 是对 pdf.js 的封装,简化了集成步骤。安装依赖:

npm install vue-pdf

示例代码:

<template>
  <pdf :src="pdfUrl" style="width: 100%;"></pdf>
</template>

<script>
import pdf from 'vue-pdf';

export default {
  components: { pdf },
  data() {
    return {
      pdfUrl: '/example.pdf',
    };
  },
};
</script>

使用 iframe 嵌入

适用于简单的 PDF 展示,无需额外依赖:

<template>
  <iframe :src="pdfUrl" width="100%" height="600px"></iframe>
</template>

<script>
export default {
  data() {
    return {
      pdfUrl: '/example.pdf',
    };
  },
};
</script>

使用第三方服务

通过 Google Docs 或其他在线服务嵌入:

vue实现pdf浏览

<template>
  <iframe 
    :src="'https://docs.google.com/viewer?url=' + encodeURIComponent(pdfUrl) + '&embedded=true'"
    width="100%"
    height="600px"
    frameborder="0"
  ></iframe>
</template>

注意事项

  • 跨域问题:若 PDF 文件位于其他域名,需确保服务器配置 CORS。
  • 性能优化:大文件可分页加载,避免一次性渲染所有页面。
  • 移动端适配:根据屏幕尺寸动态调整 scale 参数或容器大小。

以上方法可根据项目需求选择,pdf.js 适合高度定制化场景,vue-pdf 适合快速集成,iframe 适合简单嵌入。

标签: vuepdf
分享给朋友:

相关文章

vue权限实现

vue权限实现

Vue 权限实现方案 基于路由的权限控制 通过路由守卫实现权限验证,在路由配置中添加meta字段标记权限要求。在router.beforeEach中检查用户权限与路由要求的匹配情况。 // rout…

computed vue 实现

computed vue 实现

computed 在 Vue 中的基本用法 Vue 的 computed 属性用于声明依赖于其他数据的计算属性。当依赖的数据变化时,计算属性会自动重新计算并缓存结果。 export defaul…

vue实现fullpage

vue实现fullpage

Vue 实现 FullPage 效果 在 Vue 中实现全屏滚动(FullPage)效果可以通过多种方式完成,以下是几种常见的方法: 使用现有库 vue-fullpage.js 安装 vue-ful…

vue实现注销

vue实现注销

实现用户注销功能 在Vue应用中实现用户注销功能通常涉及清除用户会话、重置应用状态并跳转到登录页面。以下是具体实现方法: 清除用户认证信息 使用Vuex或Pinia管理用户状态时,需在注销时重置存储…

vue 实现modal

vue 实现modal

Vue 实现 Modal 的方法 使用 Vue 原生组件 通过 Vue 的组件系统可以轻松实现 Modal。创建一个可复用的 Modal 组件,通过 props 控制显示与隐藏。 <templ…

vue 实现弹窗

vue 实现弹窗

Vue 实现弹窗的方法 在 Vue 中实现弹窗功能可以通过多种方式完成,以下是几种常见的方法: 使用组件和 v-if/v-show 控制显示 创建一个独立的弹窗组件,通过 v-if 或 v-show…