目录

How do I use the Web component to download PDF files and display them to users?

Question

How do I use WebView to load a specified URL for downloading and displaying a PDF file?

Answer

Use the onLoadIntercept method to determine whether to download PDF files. Use the request.agent.create method to download PDF files.

Specifically, use the request module to download the online PDF file to the sandbox path, and then use the Web component to load the PDF file and display it to users.

Add the network access permission ohos.permission.INTERNET to the module.json5 configuration file in the project.

Reference code

import { webview } from '@kit.ArkWeb';
import { common } from '@kit.AbilityKit';
import { request } from '@kit.BasicServicesKit';

let context = AppStorage.get("context") as UIContext;
let filesDir = context.getHostContext()!.filesDir;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'https://www-file.huawei.com/minisite/media/annual_report/annual_report_2023_cn.pdf',
  title: 'createTest',
  description: 'Sample code for create task',
  mode: request.agent.Mode.FOREGROUND,
  overwrite: true,
  method: 'get',
  saveas: filesDir + '/test.pdf',
  network: request.agent.Network.WIFI,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: 'it is a secret'
};
let createOnCallback = (progress: request.agent.Progress) => {
  console.info('download task completed.');
  context.getPromptAction().showToast({
    message: 'Download completed',
    duration: 2000
  });
};

@Entry
@Component
struct Index {
  controller: webview.WebviewController = new webview.WebviewController();
  @State uri: string = '';
  @State isChange: boolean = false;

  build() {
    Column() {
      Button('Refresh UI')
        .width('200vp')
        .onClick(() => {
          this.controller.loadUrl('file://' + filesDir + '/test.pdf');
        })
        .margin({ bottom: '20vp' })
      Web({ src: $rawfile('WebDownloadPDF.html'), controller: this.controller })
        .fileAccess(true)
        .domStorageAccess(true)
        .onPageBegin((event) => {
          request.agent.create(this.getUIContext().getHostContext(), config).then((task: request.agent.Task) => {
            task.on('completed', createOnCallback);
            console.info(`Succeeded in creating a download task. result: ${task.config}`);
            task.start();
          }).catch((err: Error) => {
            console.error(`Failed to create a download task, message: ${err.message}`);
          });
        })
    }
  }
}