HarmonyOS 鸿蒙Next 预览pdf文件

HarmonyOS 鸿蒙Next 预览pdf文件
1、使用filePreview
2、使用web组件

在线pdf(网址是直接下载的,不是直接可以预览的),先下载再预览

typescript 复制代码
import media from '@ohos.multimedia.media';

import web_webview from '@ohos.web.webview';

import { request } from '@kit.BasicServicesKit';

import common from '@ohos.app.ability.common';

import fs from '@ohos.file.fs';

@Entry

@Component

struct WebViewPageDemo {

  webviewController: web_webview.WebviewController = new web_webview.WebviewController();

  @State fileUrl: string = ''

  @State title: string = ''

  path=''

  hasFile(filePath:string){

    let b = fs.accessSync(filePath)

    return b

  }

  aboutToAppear() {

    const context = getContext(this) as common.UIAbilityContext

    this.path=context.filesDir+'/1700182405099.pdf'

    console.log('demo ', this.path)

    console.log(this.hasFile(this.path)+'123456')

    if(!this.hasFile(this.path)) {

      request.downloadFile(context, {

        url: 'https://prdc-ams.oss-cn-shenzhen.aliyuncs.com/1700182405099.pdf',

        filePath: this.path

      }).then((data: request.DownloadTask) => {

        data.on('complete', () => {

          console.log('demo complete', this.path)

          this.fileUrl = this.path

        })

        data.on('fail', (err) => {

          console.log('demo fail', this.path)

          this.fileUrl = this.path

        })

      })

    }

  }

  build(){

    Column(){

      Button('loadUrl').onClick(()=>{

        this.webviewController.loadUrl('file://'+this.path)

      })

      Web({src: '', controller: this.webviewController})

        .javaScriptAccess(true)

        .domStorageAccess(true)

        .verticalScrollBarAccess(true)

        .fileAccess(true)

        .height('100%')

        .width('100%').onControllerAttached(() => {

        this.webviewController.loadUrl('file://'+this.path)

      })

    }

    .height('100%')

    .width('100%')

  }

}

3、使用PdfView
PdfView使用的坑

如果是在线pdf,可下载到本地沙箱,然后获取本地地址进行预览
文件目录与路径

typescript 复制代码
import { pdfService, pdfViewManager, PdfView } from '@kit.PDFKit'
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

@Entry
@Component
struct PDFView {
  private controller: pdfViewManager.PdfController = new pdfViewManager.PdfController();

  aboutToAppear(): void {
    let context = getContext() as common.UIAbilityContext;
    let dir: string = context.filesDir//files文件下
    let filePath: string = dir + "/" + '文件名';

    (async () => {
      let loadResult1: pdfService.ParseResult = await this.controller.loadDocument(filePath);
      if (pdfService.ParseResult.PARSE_SUCCESS === loadResult1) {
        hilog.info(0x0000, 'aboutToAppear', 'PdfView Component has been successfully loaded!');
      }
    })()
  }

  build() {
    Column() {
      Row() {
        PdfView({
          controller: this.controller,
          pageFit: pdfService.PageFit.FIT_WIDTH,
          showScroll: true
        })
          .id('pdfview_app_view')
          .layoutWeight(1)
      }
      .width('100%')
      .height('100%')
    }
  }
}

预览本地rawfile中的pdf

typescript 复制代码
import { pdfService, pdfViewManager, PdfView } from '@kit.PDFKit'
import { common } from '@kit.AbilityKit';
import { fileIo } from '@kit.CoreFileKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

@Entry
@Component
struct Index {
  private controller: pdfViewManager.PdfController = new pdfViewManager.PdfController();

  aboutToAppear(): void {
    let context = getContext() as common.UIAbilityContext;
    let dir: string = context.filesDir
    // 确保在工程目录src/main/resources/rawfile里存在input.pdf文档
    let filePath: string = dir + '/input.pdf';
    let res = fileIo.accessSync(filePath);
    if (!res) {
      let content: Uint8Array = context.resourceManager.getRawFileContentSync('rawfile/input.pdf');
      let fdSand =
        fileIo.openSync(filePath, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE | fileIo.OpenMode.TRUNC);
      fileIo.writeSync(fdSand.fd, content.buffer);
      fileIo.closeSync(fdSand.fd);
    }
    (async () => {
      // 该监听方法只能在文档加载前调用一次
      this.controller.registerPageCountChangedListener((pageCount: number) => {
        hilog.info(0x0000, 'registerPageCountChanged-', pageCount.toString());
      });
      let loadResult1: pdfService.ParseResult = await this.controller.loadDocument(filePath);
      // 注意:这里刚加载文档,请不要在这里立即设置PDF文档的预览方式
    })()
  }

  build() {
    Row() {
      PdfView({
        controller: this.controller,
        pageFit: pdfService.PageFit.FIT_WIDTH,
        showScroll: true
      })
        .id('pdfview_app_view')
        .layoutWeight(1);
    }
    .width('100%')
    .height('100%')
  }
}
相关推荐
song5019 小时前
鸿蒙 Flutter 图像识别进阶:物体分类与花卉识别(含离线模型)
人工智能·分布式·python·flutter·3d·华为·分类
waeng_luo9 小时前
[鸿蒙2025领航者闯关] HarmonyOS深色模式实现
harmonyos·鸿蒙2025领航者闯关·鸿蒙6实战·开发者年度总结
灯前目力虽非昔,犹课蝇头二万言。10 小时前
HarmonyOS笔记9:UIAbility之间的切换和数据的传递
笔记·harmonyos
花启莫你是不是傻10 小时前
在鸿蒙中调用 FFmpeg 命令行工具
华为·harmonyos
L、21811 小时前
性能调优实战:Flutter 在 OpenHarmony 上的内存、渲染与启动速度优化指南
javascript·华为·智能手机·electron·harmonyos
5008412 小时前
鸿蒙 Flutter 分布式硬件调用:跨设备摄像头 / 麦克风共享
分布式·flutter·华为·electron·wpf·开源鸿蒙
m0_6855350812 小时前
偶次非球面介绍
华为·光学·光学设计·光学工程·镜头设计
5008413 小时前
存量 Flutter 项目鸿蒙化:模块化拆分与插件替换实战
java·人工智能·flutter·华为·ocr
0x0415 小时前
鸿蒙应用开发笔记:签名文件
harmonyos
马剑威(威哥爱编程)16 小时前
【鸿蒙开发案例篇】鸿蒙6.0计算器实现详解
华为·harmonyos