uniapp + vue2 + pfdjs + web-view 实现安卓、iOS App PDF预览

文章目录

概要

在使用uniapp开发安卓、iOS APP的时候遇到一个需求,预览PDF,特此记录

  1. 下载pdfjs 解压到static文件夹中 pdfjs
  2. githup地址

技术栈

uniapp + vue2 + pfdjs + webview

完整代码

javascript 复制代码
<template>
  <view class="pdf-module" style="width: 100%; height: 100vh">
    <web-view :src="allUrl" :webview-styles="webviewStyles"></web-view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      allUrl: '',
      viewerUrl: '/static/pdf/web/viewer.html',
      webviewStyles: {
        progress: { color: '#007aff' }
      }
    }
  },
  onLoad(option) {
    const encodedPdfUrl = encodeURIComponent(option.url)
    const baseUrl = this.getBaseUrl()
    this.allUrl = `${baseUrl}${this.viewerUrl}?file=${encodedPdfUrl}`
  },
  methods: {
    getBaseUrl() {
      const platform = uni.getSystemInfoSync().platform
      return platform === 'ios' ? '/' : ''
    }
  }
}
</script>
<style scoped>
.pdf-module {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
</style>

效果图

小结

javascript 复制代码
注释 / 删除 同源校验逻辑
// 原错误代码(大概1802行)
if (fileOrigin !== viewerOrigin) {
  throw new Error('file origin does not match viewer\'s');
}

// 修改后(注释掉校验)
// if (fileOrigin !== viewerOrigin) {
//   throw new Error('file origin does not match viewer\'s');
// }
相关推荐
支支დ15 分钟前
VO by Vercel 前端特定优势:为什么它是构建 AI 应用的新范式
前端·人工智能
天空之城--39 分钟前
Android Koin 完全指南:从原理到实践
android
香芋芋圆42 分钟前
AI 冲击内卷之下,普通前端如何破局?WebGIS—— 低门槛突围赛道
前端·javascript·人工智能·学习·职场发展
INS_KF1 小时前
【编程笔记】成员函数中两个 const 的区别(const Data &getData() const;)
前端·javascript·笔记
宿6742 小时前
vue3-async
前端·javascript·vue.js
zhangphil2 小时前
Android main thread主线程Choreographer doFrame发生FullSuspendCheck
android
YXWik62 小时前
记录前端请求接口在浏览器请求响应的Preview和Response展示的一样的问题
前端
2501_928996222 小时前
GPT-4o换DeepSeek迁移成本多少?中科热备解析API聚合平台技术账本
前端·数据库·人工智能
东风破_2 小时前
从跨域到 WebSocket:前端跨域方案、SSE 与双向实时通信详解
前端·后端
原则猫2 小时前
TS 类型工具
前端