实现pdf文件预览

前言

工作上接到的一个任务,实现pdf的在线预览,其实uniapp中已经有对应的apiuni.openDocument(OBJECT)(新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx。)**实现了相关功能,但是会跳转到第三方应用打开,其实还是先下载再预览,所以上级特别强调的是:在app内线上预览

环境

  • 开发技术:uniapp,uni-ui
  • 兼容环境:android,ios和h5

相关知识

  • web-view:web 浏览器组件,可以用来承载网页的容器,会自动铺满整个页面,如果不想铺满页面,需要设置样式,比如<web-view :style="{'height':windowHeight}" style="width: 100%;" :src="allUrl"></web-view>
  • uni.getSystemInfo(callback):异步获取系统信息,调用成功的话会返回:系统环境、手机型号、app名称、版本、屏幕宽高等等
  • encodeURIComponent():信息加密,对应解密方法:decodeURIComponent()

具体实现

  1. 下载pdf.js官网地址
  2. 将pdf.js文件包中的web和build复制到项目文件(/hybrid/html/)下
  3. 新建一个vue文件,如file-preview.vue,并且在page.json中注册
{
    
    
			"path": "pages/file-preview/file-preview",
			"style": {
    
    
				"navigationBarTextStyle": "black"
			}
},
  1. 在file-preview.vue中添加如下代码:
<template>
	<view>
		<web-view :style="{'height':windowHeight}" style="width: 100%;"  :src="allUrl"></web-view>
	</view>
</template>

<script>
	// import globalConfig from '@/config'
	export default {
    
    
		data() {
    
    
			return {
    
    
				// pdf.js中的build和web文件存储在该项目的/hybrid/html/路径下
				viewerUrl: '/hybrid/html/web/viewer.html',
				allUrl:'',
				 windowHeight: "200px"
			}
		},
		onLoad(option) {
    
    
			uni.getSystemInfo({
    
    
			    success: (res) => {
    
    
			        this.windowHeight = (res.windowHeight-10)+"px";
			} })
			let url=encodeURIComponent(option.url)
			this.allUrl=this.viewerUrl+'?file='+url;
		}
	}
</script>

其中 option为其他页面传过来的参数, option.url为文档流路径,例如:url=‘http://58.49.74.231:85/UploadFile/Get?fileName=汇报准备工作_S_20191101170956271.pdf’

  1. 如果文件流的域名pdf.js的域名不相同,会报错,需要在web/viewer.js中吧跨域报错的信息注释掉

https://img-blog.csdnimg.cn/20200704144622373.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTg4NjQyMQ==,size_16,color_FFFFFF,t_70

参考链接

如何实现高性能的在线 PDF 预览

猜你喜欢

转载自blog.csdn.net/weixin_41886421/article/details/129328687