UNIAPP - 微信小程序做H5 PDF預覽


微信自帶的 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>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM