其实我常常会纠结今天要写什么内容。
因为希望能够保持每日更新,所以要写的内容不能太难——最好是半天可以搞出demo并且输出文章,所以很多东西浅尝辄止,并没有深入研究,还写出了一些bug 🐛
今天又浅浅的研究了下在Vue3中如何预览PDF
vue-pdf-embed
刚开始尝试 vue3-pdfjs,可以很快做出预览界面,但它没有自带打印功能,所以继续在github中翻啊翻。
最终选择了vue-pdf-embed https://github.com/hrynko/vue-pdf-embed#examples,它的功能强大一些,可以满足预览和打印的功能。
npm install vue-pdf-embed
缩放
初始化时获取容器宽度,把组件的width设为容器宽度数值,然后通过调整width的值来控制缩放。
// 设置初始宽度
onMounted(() => {
wpWidth = wpRef.value.clientWidth
width.value = wpWidth
})
function zoom(type: number) {
if ((scale.value < 0.3 && type === -1) || (scale.value > 5 && type === 1)) return
scale.value = scale.value + type * 0.1
width.value = scale.value * wpWidth
}
打印
调用print(),配置参数
print resolution (number
) 分辨率,
filename (string
),
all pages flag (boolean
)
function print() {
pdfRef.value.print(150, null, true)
}
完整代码
<!-- 样式使用了tailwind CSS -->
<template>
<div class="m-4 shadow">
<!-- v-adaptive是自定义的一个指令,详见:https://juejin.cn/post/7232106423244243002 -->
<div v-adaptive>
<vue-pdf-embed
ref="pdfRef"
:source="pdfSource"
:page="page"
:width="width"
class="transition-all"
@password-requested="handlePasswordRequest"
@rendered="handleDocumentRender"
/>
</div>
<div class="flex items-center justify-center py-2" ref="wpRef">
<el-button :disabled="page <= 1" @click="page--">❮</el-button>
<span class="mx-4">{{ page }} / {{ pageCount }}</span>
<el-button :disabled="page >= pageCount" @click="page++">❯</el-button>
<i-ep:zoom-out
@click="zoom(-1)"
class="ml-8 text-lg cursor-pointer"
:class="scale < 0.3 ? 'text-gray-300 cursor-not-allowed ' : ''"
></i-ep:zoom-out>
<i-ep:zoom-in
@click="zoom(1)"
class="ml-4 text-lg cursor-pointer"
:class="scale > 5 ? 'text-gray-300 cursor-not-allowed ' : ''"
></i-ep:zoom-in>
<el-button @click="print" class="ml-8">打印</el-button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import VuePdfEmbed from 'vue-pdf-embed'
const pdfRef = ref()
const wpRef = ref()
let pdfSource = ref('/L16 心动-编配谱.pdf')
let isLoading = ref(true)
let page = ref(1)
let scale = ref(1)
let pageCount = ref(0)
let wpWidth = 0
let width = ref(0)
onMounted(() => {
wpWidth = wpRef.value.clientWidth
width.value = wpWidth
})
function handleDocumentRender() {
isLoading.value = false
pageCount.value = pdfRef.value.pageCount
}
function zoom(type: number) {
if ((scale.value < 0.3 && type === -1) || (scale.value > 5 && type === 1)) return
scale.value = scale.value + type * 0.1
width.value = scale.value * wpWidth
}
function print() {
pdfRef.value.print(150, null, true)
}
function handlePasswordRequest(callback: any, retry) {
callback(prompt(retry ? 'Enter password again' : 'Enter password'))
}
</script>
项目地址
本项目GIT地址:github.com/lucidity99/…
如果有帮助,给个star ✨ 点个赞👍