【VuePdfEmbed】十行代码教会你在Vue3项目中完成PDF预览及下载

时隔两年,我又发布了blog,一文教会你使用VuePdfEmbed

Vue3项目使用vue-pdf-embed完成对pdf的预览和下载功能

废话不多说,直接实战

效果图

在这里插入图片描述

1.安装VuePdfEmbed

官方文档地址https://www.npmjs.com/package/vue-pdf-embed

npm i vue-pdf-embed或者yarn add vue-pdf-embed

或直接引入cdn地址 <script src="https://unpkg.com/vue-pdf-embed"></script>

2.在项目中使用VuePdfEmbed
import VuePdfEmbed from "vue-pdf-embed"; // 引入依赖

const route = useRoute()
const pdfSource = reactive({
  url: route.query.url, // 你的pdf地址 URL、Base64、二进制均可
  cMapUrl: "https://cdn.jsdelivr.net/npm/pdfjs-dist@2.16.105/cmaps/", //前缀不可修改
  cMapPacked: true,
  page: 1, //当前页码 如设置只会显示当前page 反之显示全部
  total: 0, // 你的pdf文件总页码
});

const loaded = e => {
  // 获取pdf文件页码总数
  pdfSource.total = e._pdfInfo.numPages
}

const handlePreview = (type) => {
  if (type === 'next') return pdfSource.page += 1
  pdfSource.page -= 1
}

const pdfref = ref(null)
const downLoad = () => {
  pdfref.value.download()
}
<template>
  <vue-pdf-embed ref="pdfref" v-if="pdfSource.url" :source="pdfSource" :page="pdfSource.page" @loaded="loaded">
    <template v-slot:after-page>
      <div class="btn-footer">
        <div class="download-btn" @click="downLoad">下载</div>
        <div class="info-btn">{{ `当前第${pdfSource.page}页,共${pdfSource.total}页` }}</div>
        <div class="last-btn" v-if="pdfSource.page > 1" @click="handlePreview('last')">上一页</div>
        <div class="next-btn" v-if="pdfSource.page < pdfSource.total" @click="handlePreview('next')">下一页</div>
      </div>
    </template>
  </vue-pdf-embed>
</template>

官方给我们提供了两个插槽,具体需求可参考上方插槽格式修改

  • after-page 下一页
  • before-page 上一页
3.常用事件
NameValueDescription
internal-link-clickeddestination page numberinternal link was clicked
loadedPDF document proxyfinished loading the document
loading-failederror objectfailed to load document
password-requestedobject with callback function and isWrongPassword flagpassword is needed to display the document
progressobject with number of loaded pages along with total number of pagestracking document loading progress
renderedfinished rendering the document
rendering-failederror objectfailed to render document
4.公共方法,需调用ref
NameArgumentsDescription
downloadfilename (string)download document
printprint resolution (number), filename (string), all pages flag (boolean)print document via browser interface
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端大斗师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值