Vue3 优雅实现 PDF 预览:vue-pdf-preview 从入门到实战
什么是 vue-pdf-preview?
-
开箱即用的 PDF 渲染、翻页、缩放
-
移动端 / PC 端自适应
-
自定义工具栏、水印、下载 / 打印功能
-
按需加载,体积轻量化
-
TypeScript 友好,适配 Vue3 的组合式 API
第一步:环境准备与安装
1. 安装依赖
npmnpm install vue-pdf-preview pdfjs-dist --save# yarnyarn add vue-pdf-preview pdfjs-dist# pnpm(推荐)pnpm add vue-pdf-preview pdfjs-dist
2. 全局注册(可选)
// main.tsimport { createApp } from 'vue'import App from './App.vue'import VuePdfPreview from 'vue-pdf-preview'import 'vue-pdf-preview/lib/style.css' // 引入样式const app = createApp(App)app.use(VuePdfPreview) // 全局注册app.mount('#app')
第二步:基础使用(最简示例)
<!-- PdfPreviewDemo.vue --><template><divclass="pdf-preview-container"><!-- 核心组件 --><vue-pdf-preview:pdf-url="pdfUrl":page="currentPage"@page-change="handlePageChange"/><!-- 简单的分页控制 --><divclass="pdf-controls"><button @click="currentPage--":disabled="currentPage <= 1">上一页</button><span>{{ currentPage }} / {{ totalPages }}</span><button @click="currentPage++":disabled="currentPage >= totalPages">下一页</button></div></div></template><scriptsetuplang="ts">import { ref, onMounted } from 'vue'// PDF地址(支持本地路径/远程URL,远程需配置跨域)const pdfUrl = ref('https://xxxx.com/static/test.pdf')// 当前页码const currentPage = ref(1)// 总页数const totalPages = ref(0)// 页码变化回调const handlePageChange = (page: number, pages: number) => {currentPage.value = pagetotalPages.value = pages}</script><stylescoped>.pdf-preview-container {width: 100%;max-width: 800px;margin: 20px auto;}.pdf-controls {display: flex;align-items: center;justify-content: center;gap: 16px;margin-top: 16px;}.pdf-controls button {padding: 8px 16px;border: none;background: #409eff;color: white;border-radius: 4px;cursor: pointer;}.pdf-controls button:disabled {background: #ccc;cursor: not-allowed;}</style>
第三步:进阶功能(自定义配置)
1. 自定义工具栏(隐藏 / 显示功能)
<vue-pdf-preview:pdf-url="pdfUrl":toolbar-config="toolbarConfig"/><script setup>// 工具栏配置:按需显示功能const toolbarConfig = ref({zoom: true, // 缩放rotate: true, // 旋转download: false, // 隐藏下载print: false, // 隐藏打印page: true, // 页码})</script>
2. 移动端适配 + 水印
<vue-pdf-preview:pdf-url="pdfUrl":watermark-text="'内部文档-禁止转发'":mobile-adaptive="true":scale="1.2" // 初始缩放比例/>
3. 加载状态与错误处理
<template><vue-pdf-preview:pdf-url="pdfUrl"@loading="handleLoading"@error="handleError"/><!-- 加载提示 --><divv-if="isLoading"class="loading-tip">PDF加载中...</div><!-- 错误提示 --><divv-if="hasError"class="error-tip">PDF加载失败:{{ errorMsg }}</div></template><scriptsetup>import { ref } from 'vue'const isLoading = ref(false)const hasError = ref(false)const errorMsg = ref('')// 加载中回调const handleLoading = (status: boolean) => {isLoading.value = status}// 错误回调const handleError = (error: Error) => {hasError.value = trueerrorMsg.value = error.messageconsole.error('PDF加载失败:', error)}</script>
总结
vue-pdf-preview是 Vue3 生态中轻量、易用的 PDF 预览组件,基于pdfjs-dist封装,无需关注底层解析逻辑;
基础使用仅需配置pdf-url,配合分页回调即可实现核心预览功能,进阶可自定义工具栏、水印、适配移动端;
开发中需注意跨域、本地路径、大 PDF 懒加载等问题,确保不同场景下的体验。
夜雨聆风