uniapp展示本地pdf + 自定义标题

概要

本文主要讲述uniapp打包的Android项目如何展示本地的PDF文件,并设置标题

需求分析

1、因为是打包的Android项目展示本地的PDF文件,首先需要拿到这个本地的PDF文件路径

2、如何在uniapp的vue页面中展示PDF,因为没有直接展示PDF文件的标签/组件,考虑使用web-view组件来进行展示PDF文件

3、直接使用web-view组件无法展示PDF,使用html先展示PDF,然后把html链接放到web-view中进行展示

4、html中如何展示PDF,把PDF转为canvas来进行展示这个PDF文件(使用开源的js实现,下载地址:https://download.csdn.net/download/ahualong1/89900189

具体实现

1、pdfviewer.vue代码

javascript 复制代码
<template>
	<view class="content">
		<web-view :src="url" @message="handlePostMessage"></web-view>
	</view>
</template>

<script>
	/* uni页面通信文档
	 * https://ask.dcloud.net.cn/article/35083
	 * 组件使用pdf.js源码修改了部分内容
	 * 只需要完成web-view监听页数并与uni通信即可
	 */
	import {
		computed
	} from "vue";
	import {uploadStudyTime} from '@/api/api.js'
	export default {
		data() {
			return {
				///hybrid/html/web/viewer.html?file=
				viewerUrl: '/hybrid/html/web/viewer.html', // 注意:静态的html文件需要放在根路径下的 hybrid/html 文件夹中
				fileUrl: "", // 要访问的本地pdf的路径
				url: '', // 最终显示在web-view中的路径
				// currentPage: 1, //初始页
				totalPage: 0, //总页码
				currentReadPage: 0, //当前页码
				SubjectId: '',
				startTime: 0,
				titleName: ''
			};
		},

		onLoad(options) {
			/* 设置标题 */
			this.fileUrl = options.url
			this.titleName = options.title
			/* 初始页面 */
			this.pageInt(); //获取pdfs数据
		},
		
		mounted() {
			// #ifdef H5
			window.addEventListener("message", this.ReceiveMessage);
			// #endif
		},
		
		//页面销毁前
		beforeDestroy() {
			// this.uploadSduyTimePage()
			uni.removeStorage({ //清除pdf留下的缓存,不干扰新的pdf载入
				key: 'pdfjs.history',
				success() {
				}
			})
		},
		methods: {
			//页面初始化
			pageInt() {
				this.url = `${this.viewerUrl}?file=${plus.io.convertLocalFileSystemURL(this.fileUrl)}` + '&titleName=' + this.titleName;
			},
			/* 
			 *	做成监听滚动条判断更好
			 * 
			 */
			//uni 组件通信 监听
			handlePostMessage(data) {
				if(data.detail.data.length == 1 && data.detail.data[0].back){
					uni.navigateBack()
					return
				}
				let arr = data.detail.data.pop()
				this.totalPage = arr[0].totalPage //总页数
				this.currentReadPage = arr[1].page + 1 //当前页数
			},
			//h5 监听
			ReceiveMessage(event) {
				if (event.data && event.data.data && event.data.data.arg) {
					this.totalPage = event.data.data.arg[0].totalPage
					this.currentReadPage = event.data.data.arg[1].page + 1
				}
			},

			//页面销毁前动作
			addBrowseRecord() {
				
			},

		}
	};
</script>

<style lang="scss" scoped>
</style>

代码中fileUrl 为uni.saveFile()保存到本地的路径,直接打开是无法展示的,需要使用plus的api:plus.io.convertLocalFileSystemURL(this.fileUrl) 将本地文件系统的URL转换为跨域可以访问的URL

2、viewer.html 文件做了部分修改

javascript 复制代码
<!-- 微信 JS-SDK 如果不需要兼容小程序,则无需引用此 JS 文件。 -->
<!-- <script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> -->
<!-- uni 的 SDK,必须引用。 -->
<script type="text/javascript" src="./uni.webview.js">
	
</script>
<script type="text/javascript">
	document.getElementById('backClickId').addEventListener('click',function(){
		uni.postMessage({
			data: {
				"back": true
			}
		});
	});
	var interval = setInterval('loadPdf()', 300);
	function loadPdf() {
		if (PDFViewerApplication.pdfDocument == null) {
			// console.info('Loading...');
		} else {
			clearInterval(interval);
			// let _iframe = document.getElementById("iframe")
			console.info('Load Success...:',PDFViewerApplication.pdfDocument);
		}
		if(location.href.includes('titleName')){
			document.getElementById('titleNameId').textContent = getParameterByName('titleName','');
		}else{
			document.getElementById('titleNameId').textContent = '资料学习';
		}
		
	};
	function getParameterByName(name, url) {
		if (!url) url = location.href;
		name = name.replace(/[\[\]]/g, '\\$&');
		var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
		    results = regex.exec(url);
		if (!results) return null;
		if (!results[2]) return '';
		return decodeURIComponent(results[2].replace(/\+/g, ' '));
	}
</script>

其中uni.postMessage 是web-view向uniapp.vue传递消息,

javascript 复制代码
uni.postMessage({
    data: {
	    "back": true
	}
			
});

方法getParameterByName 是获取打开的链接获取参数的方法

运行项目到模拟器或真机进行展示PDF,就OK了。

可以查看项目中 pages-> pdfvierer->pdfvierer.vue页面

项目下载地址:https://download.csdn.net/download/ahualong1/89900184

相关推荐
bin91533 分钟前
DeepSeek 助力 Vue 开发:打造丝滑的二维码生成(QR Code)
前端·javascript·vue.js·ecmascript·deepseek
@LitterFisher7 分钟前
Excell 代码处理
前端·javascript·excel
尚学教辅学习资料18 分钟前
基于SpringBoot+Vue+uniapp的高校招聘小程序+LW参考示例
spring boot·uni-app·招聘系统
m0_748230941 小时前
Redis 通用命令
前端·redis·bootstrap
YaHuiLiang2 小时前
一切的根本都是前端“娱乐圈化”
前端·javascript·代码规范
-优势在我2 小时前
Android TabLayout 实现随意控制item之间的间距
android·java·ui
hedalei2 小时前
android13修改系统Launcher不跟随重力感应旋转
android·launcher
岑梓铭3 小时前
uniapp邪门事件
uni-app
ObjectX前端实验室3 小时前
个人网站开发记录-引流公众号 & 谷歌分析 & 谷歌广告 & GTM
前端·程序员·开源
CL_IN3 小时前
企业数据集成:实现高效调拨出库自动化
java·前端·自动化