最近有在做一个移动端的应用,应用里涉及到大量的js游戏开发,使用Android原生做不太合适,就选择了uniapp,其中有一个功能是读取本地的pdf文件并展示。在网上查了点资料都是用pdf.js来开发,具体的实现方式大家可以参考 http://mozilla.github.io/pdf.js/getting_started/   

<template>
	<view class="content"><web-view :src="url"></web-view></view>
</template>

<script>
export default {
	data() {
		return {
			// pdf.js的viewer.htm所在路径
			// 注意:静态的html文件需要放在根路径下的 hybrid/html 文件夹中
			viewerUrl: '/hybrid/html/web/viewer.html',
			// 要访问的pdf的路径
			fileUrl: 'http://*******',
			// 最终显示在web-view中的路径
			url: ''
		};
	},
	onLoad() {
		// h5,使用h5访问的时候记得跨域
		// #ifdef H5
		this.url = `${this.viewerUrl}?file=${encodeURIComponent(this.fileUrl)}`;
		// #endif
		// 在安卓和ios手机上
		// 判断是手机系统:安卓,使用pdf.js
		// #ifdef APP-PLUS
		// console.log(plus.os.name )
		if(plus.os.name === 'Android') {
			this.url = `${this.viewerUrl}?file=${encodeURIComponent(this.fileUrl)}`;
			console.log(this.url  )
		}
		// ios,直接访问pdf所在路径
		else {
			this.url = encodeURIComponent(this.fileUrl);
		}
		// #endif
	},
	methods: {}
};
</script>

<style>
</style>

这里fileUrl是在线文档地址是没问题的如 http://***.pdf 可以直接显示,只有加载速度的问题,但是如果是本地的文件的话,会报错,显示文件不存在,这时需要做如下的修改把本地URL路径转换成平台绝对路径 api :  convertLocalFileSystemURL

<template>
	<view class="content"><web-view :src="url"></web-view></view>
</template>

<script>
export default {
	data() {
		return {
			// pdf.js的viewer.htm所在路径
			// 注意:静态的html文件需要放在根路径下的 hybrid/html 文件夹中
			viewerUrl: '/hybrid/html/web/viewer.html',
			// 要访问的pdf的路径
			fileUrl: '/static/1.pdf',
			// 最终显示在web-view中的路径
			url: ''
		};
	},
	onLoad() {
		// h5,使用h5访问的时候记得跨域
		// #ifdef H5
		this.url = `${this.viewerUrl}?file=${encodeURIComponent(this.fileUrl)}`;
		// #endif
		// 在安卓和ios手机上
		// 判断是手机系统:安卓,使用pdf.js
		// #ifdef APP-PLUS
		// console.log(plus.os.name )
		if(plus.os.name === 'Android') {
            //将本地URL路径转换成平台绝对路径
			this.fileUrl = plus.io.convertLocalFileSystemURL(this.fileUrl)
			this.url = `${this.viewerUrl}?file=${encodeURIComponent(this.fileUrl)}`;
			console.log(this.url  )
		}
		// ios,直接访问pdf所在路径
		else {
			this.url = encodeURIComponent(this.fileUrl);
		}
		// #endif
	},
	methods: {}
};
</script>

<style>
</style>

这样pdf.js 加载显示本地pdf文件就没问题了

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐