HarmonyOS鸿蒙Next中应用内Web组件打开本地PDF和访问远程PDF,出现异常如何解决
HarmonyOS鸿蒙Next中应用内Web组件打开本地PDF和访问远程PDF,出现异常如何解决
【问题现象】
打开本地PDF异常:通过request.downloadFile下载pdf文件到本地,然后webview打开本地文件地址,白屏。
访问远程PDF异常:在应用内通过webview 打开一个远程的pdf文件地址,webview 中顶部bar上有下载和打印功能,点击时无效。
【背景知识】
通过setDownloadDelegate()向Web组件注册一个DownloadDelegate来监听页面触发的下载任务。资源由Web组件来下载,Web组件会通过DownloadDelegate将下载的进度通知给应用。
下载完成后,通过loadUrl()接口中传入PDF文件路径,来加载PDF文档。
参考材料
【解决方案】
-
远程PDF文件下载解决方案
通过setDownloadDelegate()向Web组件注册一个DownloadDelegate来监听页面触发的下载任务,并完成下载任务。
import BusinessError from '[@ohos](/user/ohos).base'; import web_webview from '[@ohos](/user/ohos).web.webview'; import window from '[@ohos](/user/ohos).window'; [@Entry](/user/Entry) [@Component](/user/Component) struct Index { private scroller: Scroller = new Scroller() controller1: web_webview.WebviewController = new web_webview.WebviewController(); delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); build() { Scroll(this.scroller) { Column() { Text($r('app.string.EntryAbility_label')).fontSize(50).fontWeight(FontWeight.Bold) Row() { Web({ src: $rawfile("index.html"), controller: this.controller1 }) .domStorageAccess(true) .onControllerAttached(() => { try { this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { // 传入一个下载路径,并开始下载。如果传入一个不存在的路径,则会下载到默认/data/storage/el2/base/cache/web/目录。 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); }) this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { // 下载进度更新 }) this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { // 下载任务失败的错误码 }) this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { // 下载结束 }) } catch (error) { } this.controller1.setDownloadDelegate(this.delegate); web_webview.WebDownloadManager.setDownloadDelegate(this.delegate) }) }.height('80%') .border({ width: 5 }) } } .scrollBar(BarState.Off) .scrollable(ScrollDirection.Vertical) } }
网页端index.html示例代码如下:
<!DOCTYPE html> <html> <body> <a href='https://www.gov.cn/zhengce/pdfFile/2023_PDF.pdf' target='_blank'>下载pdf</a> </body> </html>
-
本地预览PDF文件
在src属性上添加前缀’file://’,即可实现webview文件预览,示例代码如下:
Web({src: 'file://'+this.fileUrl, controller: this.webviewController})
更多关于HarmonyOS鸿蒙Next中应用内Web组件打开本地PDF和访问远程PDF,出现异常如何解决的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于HarmonyOS鸿蒙Next中应用内Web组件打开本地PDF和访问远程PDF,出现异常如何解决的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
远程PDF文件下载异常
确保通过setDownloadDelegate()
正确注册DownloadDelegate
,并在onBeforeDownload
中指定有效下载路径。下载完成后,使用loadUrl()
加载PDF文件。
本地PDF文件打开白屏
在Web
组件的src
属性前添加file://
前缀,确保文件路径正确。例如:Web({src: 'file://' + this.fileUrl, controller: this.webviewController})
。
Webview顶部bar下载和打印功能无效
确保DownloadDelegate
正确实现下载逻辑,并检查Webview的配置是否支持相关功能。