zl程序教程

您现在的位置是:首页 >  前端

当前栏目

UNIAPP - 微信小程序做H5 PDF预览

H5PDF微信程序 预览 uniapp
2023-09-11 14:14:36 时间

微信自带的 openDocument API给QQ浏览器放水了.

 

一些资料我们又不能让用户那么轻易的下载到,所以只能利用webview来实现一个pdf预览 , 目前来说对移动端比较友好的当属:pdfh5 这个插件,作者也挺良心的一直在更新.

下载示例下来以后

 

 

一、把示例的模板调整一下 (一定要看注释

 

<!DOCTYPE html>
<html>
	<head>
		<meta name="viewport" content="width=device-width,initial-scale=1">
		<title></title>
		<link rel="stylesheet" type="text/css" href="../style.css" />
		<link rel="stylesheet" type="text/css" href="../pdfh5.css" />
		<!-- 注意,下面这个样式一定要加上!否则会计算不精准造成PDF文件底部空白 -->
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}

			html,
			body,
			#app {
				width: 100%;
				height: 100%;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<div id="demo"></div>
		</div>
		<script src="../pdf.js" type="text/javascript" charset="utf-8"></script>
		<script src="../pdf.worker.js" type="text/javascript" charset="utf-8"></script>
		<script src="../jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="../pdfh5.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
		
			/** 这里把url转为对象取值
			 * @param {String} val https://www.baidu.com?title=hello&src=https://www.file.com/hello.pdf
			 * @return {} {title:"hello",src:"https://www.file.com/hello.pdf"}
			 * **/
			function url2Object(val = '', unDecodeURI = true) {
				let result = {};
				const query = val.split('?')[1];
				const arr = query.split('&');
				arr.forEach((item, idx) => {
					let param = item.split('='),
						name = param[0],
						value = param[1] || ''
					if (name) {
						result[name] = value;
					}
				});
				return result;
			}


			// 获取地址url
			let win = window.location.href;
			// 经过 encodeURIComponent 加密的字符串需要用 decodeURIComponent 解码
			let url = decodeURIComponent(url2Object(win).src);
			let name = decodeURIComponent(url2Object(win).title);

			document.title = decodeURIComponent(name);
			
			let pdfh5 = new Pdfh5('#demo', {
				// 这里放pdf文件路径即可
				pdfurl: url
			});
		</script>
	</body>
</html>

 

  

 

二、微信小程序传值模板

特别要注意的是这里使用了 encodeURIComponent 加密,浏览器端就要使用 decodeURIComponent  解码.

<template>
	<view><web-view :src="websrc"></web-view></view>
</template>

<script>
export default {
	data() {
		return {
			websrc: ''
		};
	},
	onLoad(options) {
		// 这里把路径拼接成:https://www.baidu.com?title=hello&src=https://www.file.com/hello.pdf , 挺简单的就是文件链接有些符号浏览器会自动转所以我们要加密
		this.websrc = `${options.url}?src=${encodeURIComponent(options.src)}&title=${encodeURIComponent(options.title)}`;
	},
	methods: {}
};
</script>

<style></style>