当前位置:首页 > VUE

vue实现pdf浏览

2026-01-17 13:00:41VUE

Vue 中实现 PDF 浏览的方法

使用 pdf.js

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

npm install pdfjs-dist

示例代码:

vue实现pdf浏览

<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

示例代码:

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 或其他在线服务嵌入:

<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 实现访问量统计的方法 使用前端计数 在 Vue 中可以通过简单的计数器实现页面访问量的统计。这种方法适合小型项目或演示用途。 // 在 Vue 组件中 data() { return {…

vue实现选区

vue实现选区

Vue 实现选区的基本方法 在Vue中实现选区功能通常涉及DOM操作和事件处理。以下是几种常见的方法: 使用原生JavaScript的Selection API 通过window.getSelec…

vue router 实现

vue router 实现

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

vue 实现打印

vue 实现打印

Vue 实现打印功能的方法 在Vue项目中实现打印功能,可以通过以下几种方式实现: 使用window.print()方法 通过调用浏览器的原生打印API实现基础打印功能,适用于简单内容打印。 //…

vue 实现全屏

vue 实现全屏

Vue 实现全屏功能 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 完成。以下是一个完整的实现方案: 安装依赖(可选) 如果需要跨浏览器兼容性更好,可以安装 scre…

vue实现链接

vue实现链接

Vue 实现链接的方法 在 Vue 中实现链接可以通过多种方式,包括使用 <router-link>、<a> 标签或编程式导航。以下是几种常见的方法: 使用 <rout…