本文原创发布在华为开发者社区

介绍

本示例通过Web组件实现文件预览,支持PDF, word, excel格式。其中,word和excel仅实现了基本预览功能,例如excel的公式和单元格样式未实现,需自行拓展。

实现文件预览功能源码链接

效果预览

请添加链接描述

使用说明

  1. 进入应用默认打开预览本地文件页面,点击“选择要预览的本地文件”按钮可选择本地文件,本地PDF,word,excel文件均可预览。
  2. 切换到预览网络PDF文件页面,可预览互联网上pdf文件资源,项目已设置网络PDF文件链接。

实现思路

本地PDF文件加载

本地PDF文件可通过Web组件直接预览,核心代码如下,源码参考

FilePreview.ets

 PDFView(uri: string) {
    if (this.isHiddenLocalProgress) {
      Progress({
        value: CommonConstants.START_VALUE,
        total: CommonConstants.TOTAL_VALUE,
        type: ProgressType.Linear
      })
        .width(CommonConstants.FULL_PERCENT)
        .height($r('app.integer.progress_height'))
        .value(this.localProgressValue)
        .color(Color.Green)
    }
    Web({ src: uri, controller: this.controller })
      .onProgressChange((event) => {
        if (event) {
          this.localProgressValue = event.newProgress;
          if (this.localProgressValue >= CommonConstants.TOTAL_VALUE) {
            this.isHiddenLocalProgress = false;
          }
        }
      })
      .fileAccess(true)
      .onErrorReceive((event) => {
        if (event) {
          console.log("onErrorReceive +++++++++++++++++" + event.error.getErrorCode() + event.error.getErrorInfo())
        }
      })
      .horizontalScrollBarAccess(true)
      .domStorageAccess(true)
  }

网络PDF文件加载

通过设置网络链接属性,能够对接互联网上的PDF文件资源。提供有效的远程PDF文件URL(REMOTE_URL),实现云端PDF资源的加载与预览。核心代码如下,源码参考

Index.ets

 TabContent() {
          Column() {
            if (this.isHiddenRemoteProgress) {
              Progress({
                value: CommonConstants.START_VALUE,
                total: CommonConstants.TOTAL_VALUE,
                type: ProgressType.Linear
              })
                .width(CommonConstants.FULL_PERCENT)
                .height($r('app.integer.progress_height'))
                .value(this.remoteProgressValue)
                .color(Color.Green)
            }
            Web({
              src: CommonConstants.REMOTE_URL,
              controller: this.controller
            })
              .onProgressChange((event) => {
                if (event) {
                  this.remoteProgressValue = event.newProgress;
                  if (this.remoteProgressValue >= CommonConstants.TOTAL_VALUE) {
                    this.isHiddenRemoteProgress = false;
                  }
                }
              })
              .horizontalScrollBarAccess(true)
              .domStorageAccess(true)
          }
        }
        .width(CommonConstants.FULL_PERCENT)
        .backgroundColor(Color.White)
        .tabBar(
          SubTabBarStyle.of($r('app.string.tab_index_two_title'))
            .indicator({ color: $r('app.color.ohos_id_color_emphasize') })
        )

本地word,excel文件加载

本地word文件加载由纯H5页面实现,通过三方库mammoth将word文件转换为HTML形式,再通过web组件预览文件。

本地excel文件加载由纯H5页面实现,使用ExcelJS加载Excel文件,再将数据导入表格库handsontable,通过web组件预览文件。


鸿蒙场景化代码
1 声望0 粉丝