欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在手机应用中用uniapp打开PDF文件的方法

最编程 2024-08-01 18:04:11
...
export default { data() { return { viewerUrl: '/hybrid/html/web/viewer.html', allUrl: '', pdfUrl: "", title: '', } }, onLoad(options) { //需要传入pdf文件的url console.log("webview==========", options) let {pdfUrl, title, show} = options uni.setNavigationBarTitle({title: options.title}) // pdfUrl="http://mdej.impc.com.cn/hlwyy/business-ggfw/fileFeign/downloadFile?fileFullPath=/hlwyy/202305/10am/f1683680443628.pdf" this.pdfUrl = pdfUrl this.title = options.title this.loadPdf(this.pdfUrl, title) }, methods: { loadPdf(pdfUrl, title) { /* #ifdef APP-PLUS */ switch (uni.getSystemInfoSync().platform) { case 'android': console.log("loadPdf", '运行Android上'); this.loadPdfOnAndroid(pdfUrl) break; case 'ios': console.log("loadPdf", '运行iOS上'); this.loadPdfOnIos(pdfUrl) break; default: console.log("loadPdf", '运行在开发者工具上'); break; } /* #endif */ /* #ifdef H5 */ this.allUrl = pdfUrl uni.setNavigationBarTitle({ title }) /* #endif */ }, async loadPdfOnAndroid(pdfUrl) { let tempFilePath = await this.downloadPdf(pdfUrl) let localFilePath = plus.io.convertLocalFileSystemURL(tempFilePath) console.log("downloadFile=======localFilePath", localFilePath) this.allUrl = this.viewerUrl + '?file=' + encodeURIComponent(localFilePath) console.log("downloadFile=======this.allUrl", this.allUrl) }, async loadPdfOnIos(pdfUrl) { let tempFilePath = await this.downloadPdf(pdfUrl) uni.openDocument({ filePath: tempFilePath, showMenu: true, success: function (res) { console.log('打开文档成功'); } }); }, downloadPdf(pdfUrl) { return new Promise(resolve => { uni.downloadFile({ url: pdfUrl, success: (res) => { if (res.statusCode === 200) { let tempFilePath = res.tempFilePath uni.getFileInfo({ filePath: tempFilePath, success: async imgInfo => { console.log("downloadPdf=======getFileInfo", imgInfo.size); if (imgInfo.size) return resolve(tempFilePath) else return resolve(await this.downloadPdf(pdfUrl)) } }) } }, async fail(err) { return resolve(await this.downloadPdf(pdfUrl)) } }); }) }, onNavigationBarButtonTap() { var url = this.pdfUrl var title = '' let index = url.lastIndexOf(".") let titleTwo = url.lastIndexOf("/") title = this.title ? (this.title + url.substring(index, url.length)) : titleTwo console.log(title, '////'); let dtask = plus.downloader.createDownload(url, { //本地路径开头使用file://,跟上手机文件本地目录storage/emulated/0,就是用户文件管理器能看到的了,之后我创建微垠作为文件夹,后缀是用于文件命名和格式修改,大家可以使用变量。 filename: "file://storage/emulated/0/mdej/" + title //利用保存路径,实现下载文件的重命名 }, function (d, status) { //d为下载的文件对象 if (status == 200) { //下载成功,d.filename是文件在保存在本地的相对路径,使用下面的API可转为平台绝对路径 let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename); plus.runtime.openFile(d.filename); //选择软件打开文件 uni.showToast({ title: '文件保存路径' + d.filename, icon: 'none', duration: 6000, }) } else { //下载失败 plus.downloader.clear(); //清除下载任务 } }) dtask.start(); } } }

推荐阅读