uni WeChat H5 implementation preview.pdf file

Using uniapp to develop H5, the customer needs to directly preview the .pdf file. At first, I thought of the method provided by uni, uni.openDocument(OBJECT)but after a closer look, the method does not support the use of h5, so I gave up decisively.
insert image description here
I also tried to use iframethe nested form, and found that it can be used when it is running on the computer, but when it comes to the real machine, it is found that this method is not working, and it directly jumps to the web browser for download.
After consulting, I found that using a plug-in can achieve the effect of online preview, which is the protagonist of this articlepdf.js

Official website

pdf.js: Click to view . As follows, the official website is also very simple.
insert image description here
You can click download to download, the following version is selected here.
insert image description here
After downloading, unzip the compressed package into the static folder of your own project,
1. Create a pdf folder in the static folder
2. Unzip the newly downloaded pdf.js compressed package in the newly created file
3. Use it when needed Add the following code to the page

<template>
<!-- 可以使用这种方式 -->
	<web-view :src="url"></web-view>
<!-- 也可以使用 -->
<iframe scrolling="none" :src="`/static/pdf/web/viewer.html?file=${fileUrl}`" style="width:100%;height:100%;"></iframe>
</template>
<script>
export default {
    
    
	data() {
    
    
		return {
    
    
			// pdf.js的viewer.htm所在路径
			viewerUrl: '/static/pdf/web/viewer.html',
			// 要访问的pdf的路径
			fileUrl: 'https://www.tt.com/test.pdf',
			// 最终显示在web-view中的路径
			url: ''
		};
	},
	onLoad() {
    
    
		// h5,使用h5访问的时候记得跨域
		// #ifdef H5
		this.url = `${
      
      this.viewerUrl}?file=${
      
      encodeURIComponent(this.fileUrl)}`;
		// #endif
		// 判断是手机系统:安卓,使用pdf.js
		// #ifdef APP-PLUS
		if(plus.os.name === 'Android') {
    
    
			this.url = `${
      
      this.viewerUrl}?file=${
      
      encodeURIComponent(this.fileUrl)}`;
		}
		// ios,直接访问pdf所在路径
		else {
    
    
			this.url = encodeURIComponent(this.fileUrl);
		}
		// #endif
	},
	methods: {
    
    }
};
</script>

6. If there is a cross-domain problem, set as follows
Directly modify the source code in viewer.js, you can also search globally file origin does not match viewerand comment the code block
insert image description here
Through the above operations, it can be perfectly realized in the project and hand over~

Guess you like

Origin blog.csdn.net/qq_38188228/article/details/123833629