index.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <template>
  2. <view class="preview-page">
  3. <view v-if="isLoading" class="loading-container">
  4. <text class="loading-text">正在加载PDF...</text>
  5. </view>
  6. </view>
  7. </template>
  8. <script setup>
  9. import { ref, onMounted } from 'vue'
  10. // 加载状态
  11. const isLoading = ref(true)
  12. onMounted(async () => {
  13. // 获取页面参数
  14. const pages = getCurrentPages()
  15. const currentPage = pages[pages.length - 1]
  16. const options = currentPage.options || {}
  17. if (options.base64) {
  18. try {
  19. // 解码base64
  20. const base64Data = decodeURIComponent(options.base64)
  21. // 将base64转换为临时文件
  22. const filePath = await base64ToTempFile(base64Data)
  23. // 打开文档预览
  24. uni.openDocument({
  25. filePath: filePath,
  26. fileType: 'pdf',
  27. showMenu: true,
  28. success: () => {
  29. isLoading.value = false
  30. // 预览打开后返回上一页
  31. setTimeout(() => {
  32. uni.navigateBack()
  33. }, 500)
  34. },
  35. fail: (err) => {
  36. console.error('打开文档失败:', err)
  37. isLoading.value = false
  38. uni.showToast({
  39. title: '打开文档失败',
  40. icon: 'none'
  41. })
  42. setTimeout(() => {
  43. uni.navigateBack()
  44. }, 1500)
  45. }
  46. })
  47. } catch (error) {
  48. console.error('处理PDF失败:', error)
  49. isLoading.value = false
  50. uni.showToast({
  51. title: '处理PDF失败',
  52. icon: 'none'
  53. })
  54. setTimeout(() => {
  55. uni.navigateBack()
  56. }, 1500)
  57. }
  58. } else {
  59. isLoading.value = false
  60. uni.showToast({
  61. title: '缺少PDF数据',
  62. icon: 'none'
  63. })
  64. setTimeout(() => {
  65. uni.navigateBack()
  66. }, 1500)
  67. }
  68. })
  69. // 将base64转换为临时文件
  70. const base64ToTempFile = (base64Data) => {
  71. return new Promise((resolve, reject) => {
  72. const fs = uni.getFileSystemManager()
  73. const fileName = `${Date.now()}.pdf`
  74. const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`
  75. fs.writeFile({
  76. filePath: filePath,
  77. data: base64Data,
  78. encoding: 'base64',
  79. success: () => {
  80. resolve(filePath)
  81. },
  82. fail: (err) => {
  83. reject(err)
  84. }
  85. })
  86. })
  87. }
  88. </script>
  89. <style lang="scss" scoped>
  90. .preview-page {
  91. width: 100%;
  92. height: 100vh;
  93. display: flex;
  94. align-items: center;
  95. justify-content: center;
  96. background-color: #f5f5f5;
  97. .loading-container {
  98. text-align: center;
  99. .loading-text {
  100. font-size: 28rpx;
  101. color: #666666;
  102. }
  103. }
  104. }
  105. </style>