使用步骤:
1.官网下载地址pdf.js
2.在项目的根目录新建hybrid文件夹,将下载的pdf.js压缩包解压后,复制到hybrid下的html文件夹中
3.在page文件夹下新建一个filePreview.vue页面,页面代码如下:
<template><view><web-view :src="allUrl"></web-view></view>
</template><script>export default {data() {return {viewerUrl: '/hybrid/html/web/viewer.html',allUrl: ''}},onLoad(options) {this.allUrl = this.viewerUrl + '?file=' + options.url;},methods: {}}
</script><style>
</style>
4.从接口处拿到数据流进行处理,将数据流转化成base64,需要用到image-tools.js,引用uniapp插件市场转base64插件,插件代码如下:
function getLocalFilePath(path) {if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {return path}if (path.indexOf('file://') === 0) {return path}if (path.indexOf('/storage/emulated/0/') === 0) {return path}if (path.indexOf('/') === 0) {var localFilePath = plus.io.convertAbsoluteFileSystem(path)if (localFilePath !== path) {return localFilePath} else {path = path.substr(1)}}return '_www/' + path
}function dataUrlToBase64(str) {var array = str.split(',')return array[array.length - 1]
}var index = 0function getNewFileId() {return Date.now() + String(index++)
}function biggerThan(v1, v2) {var v1Array = v1.split('.')var v2Array = v2.split('.')var update = falsefor (var index = 0; index < v2Array.length; index++) {var diff = v1Array[index] - v2Array[index]if (diff !== 0) {update = diff > 0break}}return update
}export function pathToBase64(path) {return new Promise(function(resolve, reject) {if (typeof window === 'object' && 'document' in window) {if (typeof FileReader === 'function') {var xhr = new XMLHttpRequest()xhr.open('GET', path, true)xhr.responseType = 'blob'xhr.onload = function() {if (this.status === 200) {let fileReader = new FileReader()fileReader.onload = function(e) {resolve(e.target.result)}fileReader.onerror = rejectfileReader.readAsDataURL(this.response)}}xhr.onerror = rejectxhr.send()return}var canvas = document.createElement('canvas')var c2x = canvas.getContext('2d')var img = new Imageimg.onload = function() {canvas.width = img.widthcanvas.height = img.heightc2x.drawImage(img, 0, 0)resolve(canvas.toDataURL())canvas.height = canvas.width = 0}img.onerror = rejectimg.src = pathreturn}if (typeof plus === 'object') {plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {entry.file(function(file) {var fileReader = new plus.io.FileReader()fileReader.onload = function(data) {resolve(data.target.result)}fileReader.onerror = function(error) {reject(error)}fileReader.readAsDataURL(file)}, function(error) {reject(error)})}, function(error) {reject(error)})return}if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {wx.getFileSystemManager().readFile({filePath: path,encoding: 'base64',success: function(res) {resolve('data:image/png;base64,' + res.data)},fail: function(error) {reject(error)}})return}reject(new Error('not support'))})
}export function base64ToPath(base64) {return new Promise(function(resolve, reject) {if (typeof window === 'object' && 'document' in window) {base64 = base64.split(',')var type = base64[0].match(/:(.*?);/)[1]var str = atob(base64[1])var n = str.lengthvar array = new Uint8Array(n)while (n--) {array[n] = str.charCodeAt(n)}return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))}var extName = base64.split(',')[0].match(/data\:\S+\/(\S+);/)if (extName) {extName = extName[1]} else {reject(new Error('base64 error'))}var fileName = getNewFileId() + '.' + extNameif (typeof plus === 'object') {var basePath = '_doc'var dirPath = 'uniapp_temp'var filePath = basePath + '/' + dirPath + '/' + fileNameif (!biggerThan(plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472', plus.runtime.innerVersion)) {plus.io.resolveLocalFileSystemURL(basePath, function(entry) {entry.getDirectory(dirPath, {create: true,exclusive: false,}, function(entry) {entry.getFile(fileName, {create: true,exclusive: false,}, function(entry) {entry.createWriter(function(writer) {writer.onwrite = function() {resolve(filePath)}writer.onerror = rejectwriter.seek(0)writer.writeAsBinary(dataUrlToBase64(base64))}, reject)}, reject)}, reject)}, reject)return}var bitmap = new plus.nativeObj.Bitmap(fileName)bitmap.loadBase64Data(base64, function() {bitmap.save(filePath, {}, function() {bitmap.clear()resolve(filePath)}, function(error) {bitmap.clear()reject(error)})}, function(error) {bitmap.clear()reject(error)})return}if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {var filePath = wx.env.USER_DATA_PATH + '/' + fileNamewx.getFileSystemManager().writeFile({filePath: filePath,data: dataUrlToBase64(base64),encoding: 'base64',success: function() {resolve(filePath)},fail: function(error) {reject(error)}})return}reject(new Error('not support'))})
}
5.页面展示如何处理,页面代码如下:
<template><view><button @click="receiveRenderData" class="app-view">查看PDF</button></view>
</template><script>import { base64ToPath } from './image-tools.js';export default {data() {return { msg: '', allUrl: '' }},onLoad() {this.changeMsg()},methods: {changeMsg() {let datats = {} //传值var _this = thisuni.request({url: '接口地址',data: datats,method: 'POST',responseType: 'arraybuffer',success: response => {if (!response) {uni.showToast({title: '协议预览失败',duration: 2000});}_this.msg = `data:application/pdf;base64,${uni.arrayBufferToBase64(response.data)}`;},fail: err => {console.log(err)}});},receiveRenderData(val) {console.log(this.msg)let result = this.msg.replace(/[\r\n]/g, '');let pdfBase64 = `data:application/pdf;base64,${result}`;this.allUrl = this.msg;base64ToPath(result).then(path => {//转成本地地址var p = plus.io.convertLocalFileSystemURL(path);let keys = 'file://' + p;uni.navigateTo({ url: '../../pages/index/filePreview?url=' + keys })}).catch(error => {console.error(error)})}}}
</script><style></style>