项目中需要用到pdf预览,这不仅仅只是前端的问题,和后端返回的http预览地址也有关系。

当后端同学返回可在线预览的地址时(文件流),我们便可以用pdf.js进行引入,看到网上一大堆教程,真正能使用的很少,现在把我踩坑经验分享给大家。

问题一:

之前在做的时候后端同学给的是下载地址,当我打开给我的路径是直接弹出下载文件,后来通过后端同学的修改,在h5上面是可以直接进行预览,但是当我在运行在真机时,地址访问出错,读取不到当前路径下的文件,搞了半天,原来后端返回的是对象存储。沟通一翻后,开始干。

先上效果图:

 

这个效果自带水印,目前下载,打印文档尚未开发,后期补充。如果想去掉右侧扩展栏,可更改源码。

如需要添加水印,请阅读:https://www.jianshu.com/p/b254109d7ad9

pdf文件需要存放到下图,红框内的文件请自己提取

 提取码 hmwy

下面是报告详情页面代码

<!-- 报告详情界面 -->
<template>
	<view id="MKBG10001A" class="page-container">
		<view class="custom-navbar" :style="{'height':`${statusBarHeight}px`}">
			<view class="custom-navbar-box">
				<text class="icon-back" @tap="back"><i class="uni-btn-icon"
						style="color: rgb(0, 0, 0); font-size: 27px;"></i></text>
				<text class="text-page-title">报告详情</text>
			</view>
		</view>
		<web-view :src="this.fileUrl"></web-view>
	</view>
</template>

<script>
	export default {
		name: 'MKBG10002A',
		components: {},
		data (){
			return {
				fileUrl: '/hybrid/html/web/viewer.html?file=' // pdf viewer的存放路径
			}
		},
		onLoad(options) {
            // encodeURIComponent 针对当前预览文件是网页链接    
			this.fileUrl += encodeURIComponent(options.fileUrl)
            // 如果是项目本地文件 文件路径同viewer.html路径
            // this.fileUrl += './demo.pdf'
		},
		onReady() {
				// #ifdef APP-PLUS
				var currentWebview = this.$scope.$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
				setTimeout(function() {
					let wv = currentWebview.children()[0]
                    // 这里的top 可以设置成固定值  '80px'
					wv.setStyle({top:statusBarHeight+'px',left: '0px', bottom: '0px'})
				}, 1000); //如果是页面初始化调用时,需要延时一下 
				// #endif 
		},
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
		}
	};
</script>
<style scoped>
	.page-container {
		position: relative;
		width: 100%;
		height: 100%;
		background: #F2F3F5;
		font-family: PingFangSC-Regular, PingFang SC;
	}
	/* 头部bar */
	.custom-navbar {
		position: fixed;
		width: 100%;
		background: #fff;
		z-index: 1000;
	}
	
	.custom-navbar-box {
		position: absolute;
		width: 100%;
		height: 88rpx;
		bottom: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		box-sizing: border-box;
		padding: 14rpx 6rpx;
	}
	
	.text-page-title {
		text-align: center;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		font-size: 36rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
	}
	.icon-back {
		position: absolute;
		left: 16rpx;
		top: 10rpx;
	}
</style>
<style>

因为未在苹果测试,所以等测试之后会反馈当前代码适不适合

Logo

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

更多推荐