小程序 H5 PDF预览(wx.openDocument)

H5嵌入小程序时,h5中使用预览、下载是正常的。唯独小程序中是不可以的。

话不多说上干货:

1、首先要在入口文件中判断当前环境是什么

const { userAgent } = window.navigator;
const ismini = /miniProgram/i.test(userAgent);		//微信小程序
if(ismini){
	const url = encodeURIComponent(`${window.location.origin}/epolicy/getDocument?        businessType=1&policyType=${policyType}&tradeTime=${tradeTime}&businessCode=${this.policyNo}`)
	window.wx.miniProgram.navigateTo({
		url: `/pages/load/onload/index?url=${url}`,
		
	});
}else{
	window.open(`${window.location.origin}/epolicy/getDocument?businessType=1&policyType=${policyType}&tradeTime=${tradeTime}&businessCode=${this.policyNo}`)
				}

2、在小程序的承接页面中/pages/load/onload/index加入代码

var config = require('../../../utils/config.js');
const app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		newsrc: true,
		name: '',
		code: '',
	},
	/**
	 * 监听页面加载
	 */
	onLoad: function(options) {
		var arr = decodeURIComponent(options.url).split("&");
		var obj = {};
		for (var i = 0; i < arr.length; i++) {
			var g = arr[i].split("=");
			obj[g[0]] = g[1];
		}
		if (obj.policyNo) {
			this.setData({
				name: '电子发票',
				code: obj.policyNo
			})
		}
		let newurl = decodeURIComponent(options.url)
		wx.request({
			url: newurl,
			header: {
				"content-type": "application/json",
			},
			responseType: "arraybuffer", //注意这里的responseType
			success: (result) => {
				var fileManager = wx.getFileSystemManager();
				var FilePath = wx.env.USER_DATA_PATH + "/" + `${this.data.code}_invoice.pdf`;
				fileManager.writeFile({
					data: result.data,
					filePath: FilePath,
					encoding: "binary", //编码方式 
					success: res => {
						this.setData({
							newsrc: false
						})
						wx.openDocument({ //我这里成功之后直接打开
							filePath: FilePath,
							showMenu: true,
							fileType: "pdf",
							success: result => {
								console.log("打开文档成功");
							},
							fail: err => {
								console.log("打开文档失败", err);
							}
						});
					},
					fail: res => {
						wx.showToast({
							title: '导出失败!',
							icon: 'none', //默认值是success,就算没有icon这个值,就算有其他值最终也显示success
							duration: 2000, //停留时间
						})
						console.log(res);
					}
				})
			},
			fail(err) {
				console.log(err)
			}
		})
	},

	/**
	 * 监听页面初次渲染完成
	 */
	onReady: function() {


	},

	/**
	 * 监听页面显示
	 */
	onShow: function() {

		if (this.data.newsrc == false) {
			this.setData({
				newsrc: true
			})
		}
	},

	/**
	 * 监听页面隐藏
	 */
	onHide: function() {

		if (this.data.newsrc == false) {
			this.setData({
				newsrc: true
			})
		}
	},

	/**
	 * 监听页面卸载
	 */
	onUnload: function() {},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {}
})

你可能感兴趣的:(小程序,pdf,微信小程序,前端,H5)