| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- <template>
- <view class="preview-page">
- <view v-if="isLoading" class="loading-container">
- <text class="loading-text">正在加载PDF...</text>
- </view>
- </view>
- </template>
- <script setup>
- import { ref, onMounted } from 'vue'
- // 加载状态
- const isLoading = ref(true)
- onMounted(async () => {
- // 获取页面参数
- const pages = getCurrentPages()
- const currentPage = pages[pages.length - 1]
- const options = currentPage.options || {}
-
- if (options.base64) {
- try {
- // 解码base64
- const base64Data = decodeURIComponent(options.base64)
-
- // 将base64转换为临时文件
- const filePath = await base64ToTempFile(base64Data)
-
- // 打开文档预览
- uni.openDocument({
- filePath: filePath,
- fileType: 'pdf',
- showMenu: true,
- success: () => {
- isLoading.value = false
- // 预览打开后返回上一页
- setTimeout(() => {
- uni.navigateBack()
- }, 500)
- },
- fail: (err) => {
- console.error('打开文档失败:', err)
- isLoading.value = false
- uni.showToast({
- title: '打开文档失败',
- icon: 'none'
- })
- setTimeout(() => {
- uni.navigateBack()
- }, 1500)
- }
- })
- } catch (error) {
- console.error('处理PDF失败:', error)
- isLoading.value = false
- uni.showToast({
- title: '处理PDF失败',
- icon: 'none'
- })
- setTimeout(() => {
- uni.navigateBack()
- }, 1500)
- }
- } else {
- isLoading.value = false
- uni.showToast({
- title: '缺少PDF数据',
- icon: 'none'
- })
- setTimeout(() => {
- uni.navigateBack()
- }, 1500)
- }
- })
- // 将base64转换为临时文件
- const base64ToTempFile = (base64Data) => {
- return new Promise((resolve, reject) => {
- const fs = uni.getFileSystemManager()
- const fileName = `${Date.now()}.pdf`
- const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`
-
- fs.writeFile({
- filePath: filePath,
- data: base64Data,
- encoding: 'base64',
- success: () => {
- resolve(filePath)
- },
- fail: (err) => {
- reject(err)
- }
- })
- })
- }
- </script>
- <style lang="scss" scoped>
- .preview-page {
- width: 100%;
- height: 100vh;
- display: flex;
- align-items: center;
- justify-content: center;
- background-color: #f5f5f5;
-
- .loading-container {
- text-align: center;
-
- .loading-text {
- font-size: 28rpx;
- color: #666666;
- }
- }
- }
- </style>
|