PDF预览页面会根据用户操作使用window.localStorage记录侧导航栏的展开状态,因此需要开启文档对象模型存储domStorageAccess权限。
当前主要包含三种PDF文档加载预览场景:
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct OnlinePdf {
controller: webview.WebviewController = new webview.WebviewController();
url: string = 'www.example.com/test.pdf'; // 使用时需要替换成真实的在线URL
build() {
Column() {
Web({
src: this.url,
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(false)
.geolocationAccess(false);
};
}
} import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct DownloadUrlPreview {
controller: webview.WebviewController = new webview.WebviewController();
delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate();
cacheDir: string = this.getUIContext().getHostContext()!.cacheDir;
build() {
Column() {
Web({
src: 'xxx.com/xxx.pdf', // 需要替换为那种打开后自动下载PDF文档的链接
controller: this.controller
})
.fileAccess(true)
.domStorageAccess(true)
.geolocationAccess(false)
.onControllerAttached(() => {
try {
this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => {
// 传入本地沙箱路径并开始下载
webDownloadItem.start(this.cacheDir + '/' + webDownloadItem.getSuggestedFileName());
});
this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => {
// 下载任务进度和速度监测处理
console.info(`download update guid: ${webDownloadItem.getGuid()}`);
});
this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => {
// 下载任务失败处理
console.error(`download failed guid: ${webDownloadItem.getGuid()}`);
});
this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => {
// 下载成功通过Web重新加载本地文件打开预览
this.controller.loadUrl(`file://${this.cacheDir}/` + webDownloadItem.getSuggestedFileName());
});
this.controller.setDownloadDelegate(this.delegate);
} catch (error) {
// 异常处理
console.error(
`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
});
};
}
} import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct SandboxPdf {
controller: webview.WebviewController = new webview.WebviewController();
url: string | Resource = this.getUIContext().getHostContext()!.filesDir + '/test.pdf';
build() {
Column() {
Web({
src: this.url,
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(true)
.geolocationAccess(false);
};
}
} import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct LocalFilePdf {
controller: webview.WebviewController = new webview.WebviewController();
url: string | Resource = $rawfile('test.pdf'); // 也可以替换成:'resource://rawfile/test.pdf'
build() {
Column() {
Web({
src: this.url,
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(false)
.geolocationAccess(false);
};
};
} 在创建Web组件时,通过WebOptions的第一个参数src加载默认PDF文档后,若需变更Web组件显示的PDF文档,不能通过状态变量动态更改src地址,而需要通过调用loadUrl()接口重新加载指定的PDF文档。
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct LoadUrlDemo {
controller: webview.WebviewController = new webview.WebviewController();
url: string | Resource = $rawfile('test.pdf'); // 也可以替换成:'resource://rawfile/test.pdf'
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
this.controller.loadUrl(this.url);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
});
Web({
src: $rawfile('test2.pdf'), // 使用时需要替换成真实的URL
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(false)
.geolocationAccess(false);
};
}
} 在PDF预览时,很多时候需要实现设置背景色、自动缩放、隐藏下载按钮等功能,这时候需要在PDF地址后面添加配置预览参数,同时配置多个参数时中间使用&符号拼接,参考如下demo:
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct EndParamDemo {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Web({
src: 'resource://rawfile/test.pdf#toolbar=0&pdfbackgroundcolor=ffffff',
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(false)
.geolocationAccess(false);
};
}
} 使用startDownload()接口发起一个下载。具体步骤如下:
示例代码如下:
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct DownloadDemo {
controller: webview.WebviewController = new webview.WebviewController();
delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate();
webCacheDir: string = this.getUIContext().getHostContext()?.cacheDir + '/web/';
@State myText: string = '未开启监听';
@State suggestedFileName: string = '';
build() {
Column() {
Text(this.myText);
Button('注册监听类')
.onClick(() => {
try {
this.myText = '已开启监听';
this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => {
console.info('will start a download.');
// 传入一个下载路径,并开始下载,如果传入一个不存在的路径,则会下载到默认/data/storage/el2/base/cache/web/目录。
webDownloadItem.start(this.webCacheDir + webDownloadItem.getSuggestedFileName());
});
this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => {
console.info(`download update guid: ${webDownloadItem.getGuid()}`);
});
this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => {
console.error(`download failed guid: ${webDownloadItem.getGuid()}`);
});
this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => {
console.info(`download finish guid: ${webDownloadItem.getGuid()}`);
this.myText = '下载完成';
this.suggestedFileName = webDownloadItem.getSuggestedFileName();
});
this.controller.setDownloadDelegate(this.delegate);
} catch (error) {
console.error(
`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
});
Button('开始下载')
.onClick(() => {
try {
// 开发者需要替换为自己想要下载的内容的地址。
this.controller.startDownload('xxx.com/xxx.pdf');
} catch (error) {
console.error(
`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
});
Button('打开下载的PDF').onClick(() => {
try {
this.controller.loadUrl(this.webCacheDir + this.suggestedFileName);
} catch (error) {
console.error(
`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
});
Web({
src: $rawfile('test.pdf'),
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(true)
.geolocationAccess(false);
};
}
} 对于一些加载比较慢的网页PDF文件,可以通过prefetchPage方法在onPageEnd阶段进行预下载,当真正去加载下一个页面的时候,如果预加载已经成功,则相当于直接从缓存中加载页面资源,速度更快。参考如下demo:
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct PrefetchDemo {
prefetchUrl: string =
'www.example.com/xxx.pdf'; // 网络PDF文件路径
private controller: WebviewController = new webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
this.controller.loadUrl(this.prefetchUrl);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
});
Web({
src: $rawfile('test.pdf'),
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(false)
.geolocationAccess(false)
.onPageEnd(() => {
try {
this.controller.prefetchPage(this.prefetchUrl);
} catch (error) {
console.error(
`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
});
};
}
} Web组件的onScroll事件无法监控到Web组件加载的PDF的滑动,因为目前PDF是以插件的形式在Web中加载的,暂不支持监听滚动条(监听不到活动位移),可以通过Web组件的onOverScroll通知网页过度滚动的偏移量的回调判断PDF是否到达顶端,底端。
Q:使用Web预览PDF时,如何判断PDF文件是否是最后一页或者滑动到底部?
A:可以通过onPdfScrollAtBottom事件来通知用户PDF页面已滚动到底,参考如下demo:
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct BottomDemo {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Web({
src: $rawfile('test.pdf'),
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(false)
.geolocationAccess(false)
.onPdfScrollAtBottom(
(eventInfo: OnPdfScrollEvent) => {
console.info(`Scroll at bottom callback called. url: ${eventInfo.url}.`);
}
);
};
};
} Q:如何监听Web组件是否加载PDF成功?
A:可以通过onPdfLoadEvent事件通知用户PDF页面加载状态,包括成功或失败,样例demo如下:
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct LoadEventDemo {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Web({
src: $rawfile('test.pdf'),
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(false)
.geolocationAccess(false)
.onPdfLoadEvent(
(eventInfo: OnPdfLoadEvent) => {
console.info(`Load event callback called. url: ${eventInfo.url}, result: ${eventInfo.result}.`);
}
);
};
};
} Q:如何预览base64格式的PDF文件?
A:可以通过data url方式直接加载,例如:
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct Base64Demo {
controller: webview.WebviewController = new webview.WebviewController();
pdfStr: string = 'data:application/pdf;base64,xxx'; // 使用时将xxx替换为PDF的base64格式数据
build() {
Column() {
Web({
src: this.pdfStr,
controller: this.controller
})
.domStorageAccess(true)
.geolocationAccess(false)
.fileAccess(false);
};
}
} Q:如何在预览PDF时显示加载进度条?
A:可以通过Progress组件结合onProgressChange事件来实现,demo如下:
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct LoadProgressDemo {
controller: webview.WebviewController = new webview.WebviewController();
// 创建变量表示进度值
@State value: number = 0;
build() {
Column() {
Progress({ value: this.value, total: 100, type: ProgressType.Capsule })
.height('200px')
.borderRadius(80);
Web({
src: $rawfile('test.pdf'),
controller: this.controller
})
.domStorageAccess(true)
.fileAccess(false)
.geolocationAccess(false)
.onProgressChange((event) => {
if (event) {
this.value = event.newProgress;
}
});
};
}
} Q:Web预览PDF时如何展示标题title?
A:使用Column嵌套Row和Web实现布局,通过onTitleReceive方法获取加载的网页的标题。参考如下demo:
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct TitleDemo {
@State title: string = '';
private webviewController: WebviewController = new webview.WebviewController();
build() {
Column() {
Row() {
Text(this.title)
.fontSize('50px')
.layoutWeight(1)
.textAlign(TextAlign.Center);
}
.width('100%')
.height(40);
Web({
src: 'xxx.com/xxx.pdf', // 运行时替换成真实的地址
controller: this.webviewController,
})
.width('100%')
.domStorageAccess(true)
.fileAccess(false)
.geolocationAccess(false)
.onTitleReceive((event) => {
if (event) {
this.title = event.title;
}
});
};
}
}