使用 Vue3 + TypeScript 实现 PDF 预览组件
简介
在现代的 Web 应用中,预览 PDF 文件是一个常见需求。本文介绍了一个基于 Vue3 和 TypeScript 的 PDF 预览组件,该组件支持分页预览、打印和下载功能。
技术栈
- Vue3
- TypeScript
- Element Plus
- unocss
- vue-pdf-embed
功能特点
- 分页预览: 支持在不同的 PDF 页面之间进行切换。
- 打印: 提供直接在浏览器中打印 PDF 的功能。
- 下载: 用户可以下载整个 PDF 文档。
- 显示所有页: 提供一个选项,用户可以选择查看所有页面。
组件代码
以下是组件的核心代码:
<script setup lang="ts">
import { ref } from "vue";
import VuePdfEmbed from "vue-pdf-embed";
const pdfUrl = "https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf";
const dialogVisible = ref(false);
const loading = ref(false);
const pdfRef = ref();
const source = ref("");
const currentPage = ref<number | undefined>(1);
const pageCount = ref(1);
const showAllPages = ref(false);
const open = (url: string = pdfUrl) => {
source.value = url;
dialogVisible.value = true;
loading.value = true;
};
const documentRender = () => {
loading.value = false;
pageCount.value = pdfRef.value.doc.numPages;
};
const showAllPagesChange = () => {
currentPage.value = showAllPages.value ? undefined : 1;
};
const handleDownload = () => {
pdfRef.value.download();
};
const handlePrint = () => {
// 如果在打印时,打印页面是本身的两倍,在打印配置 页面 设置 仅限页码为奇数的页面 即可
pdfRef.value.print();
};
defineExpose({
open
});
</script>
<template>
<div>
<el-dialog v-model="dialogVisible" title="预览" width="80%" align-center destroy-on-close>
<div flex="~ justify-between items-center">
<div>
<el-pagination
v-if="!showAllPages"
v-model:current-page="currentPage"
layout="prev, pager, next"
:page-size="1"
:total="pageCount"
hide-on-single-page
/>
<div v-else>共{{ pageCount }}页</div>
</div>
<div flex="~ items-center">
<el-checkbox v-model="showAllPages" @change="showAllPagesChange">展示所有</el-checkbox>
<el-tooltip effect="dark" content="下载">
<SvgIcon
ml-2
color="#000"
cursor-pointer
@click="handleDownload"
:icon-style="{ width: '20px', height: '20px' }"
name="download"
/>
</el-tooltip>
<el-tooltip effect="dark" content="打印">
<SvgIcon
ml-2
color="#000"
cursor-pointer
@click="handlePrint"
:icon-style="{ width: '20px', height: '20px' }"
name="printing"
/>
</el-tooltip>
</div>
</div>
<el-scrollbar mt-3 height="75vh" v-loading="loading">
<vue-pdf-embed ref="pdfRef" container overflow-auto :source="source" :page="currentPage" @rendered="documentRender" />
</el-scrollbar>
</el-dialog>
</div>
</template>
<style lang="scss" scoped></style>
总结
通过组合 Vue3、TypeScript 和其他现代前端技术,我们创建了一个功能丰富的 PDF 预览组件。这个组件提供了用户友好的分页预览、打印和下载功能,为开发者在 Web 应用中集成 PDF 预览提供了便捷的解决方案。
希望这篇文章能够帮助你更好地了解如何使用 Vue3 和 TypeScript 实现 PDF 预览功能!如果你有任何问题或建议,请随时提出。
转载自:https://juejin.cn/post/7360601384494841895