鸿蒙系统中实现保存pdf至本地

最近开发过程中遇到这样一个需求,需要将发票保存到本地,在网上看了一些案例,没有实现所需要的功能,并且都需要声明额外权限,于是我决定自己实现,在这里记录下我的实现过程。

pdf 展示方式

在下载之前首先是将 pdf 展示出来,ArkUI 中有一个 Web 组件,可以非常方便的实现这个功能。 Web 组件的用途就是用来展示和下载 web 内容,其能力由@ohos.web.webview 提供,因此也可以通过 url 来展示和下载 pdf。

ts 复制代码
Web({
  src: this.pdfUrl, // 加载网络PDF文档
  controller: this.controller,
}).domStorageAccess(true); // domStorageAccess 方法用于控制Web中对文档对象模型存储(DOM Storage API)的启用状态,若将其设置为 false,会影响到PDF文件在Web中的预览功能

实现思路

由于发票是由第三方平台所返回的,格式不固定,存在图片格式及已.pdf 结尾的 PDF 文件和无后缀的 PDF 文件,因此需要先判断文件类型,然后进行不同的处理。第二步下载文件到应用沙箱,第三部利用文件选择器将文件复制到公共目录下。

首先是通过url后缀判断文件类型

ts 复制代码
function getFileExtension(url: string): string {
  // 去除URL中的查询参数和锚点
  const cleanUrl = url.split('?')[0].split('#')[0];
  const filename = cleanUrl.substring(cleanUrl.lastIndexOf('/') + 1);
  // 提取扩展名(带点判断)
  const lastDotIndex = filename.lastIndexOf('.');
  if (lastDotIndex > 0) {
    // 确保点不在文件名开头
    return filename.substring(lastDotIndex).toLowerCase();
  }
  return '';
}

然后第二步,就是先将文件下载到沙箱中

ts 复制代码
 @State pdfUrl: string = '' // pdf地址
 ... // 省略其他代码 
 // 保存到本地沙箱
async saveToSandbox(){
      const sandboxDir = getContext().cacheDir;
    // 创建唯一文件名
      const fileExtension = this.getFileExtension(this.pdfUrl);
      const fileName = `invoice_${new Date().getTime()}${fileExtension ? fileExtension : '.pdf'}`;
      const fullPath = `${sandboxDir}/${fileName}`; // 直接拼接路径
      // 下载文件到沙箱中
      await this.downloadPDF(fullPath)
      // 保存到Download中
      this.copyToDownload(fileName,fullPath)
 }


 // 根据沙箱路径下载,这是一个异步过程
  async downloadPDF(fullPath: string): Promise<void> {
    this.controller.startDownload(this.pdfUrl);
    return new Promise((resolve, reject) => {
      try {
        this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => {
          // 传入下载路径,并开始下载。
          webDownloadItem.start(fullPath);
        })
        this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => {
          console.log("download failed guid: " + webDownloadItem.getGuid());
          ToastUtil.showToast('加载失败')
          reject()
        })
        this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => {
          console.log("download finish guid: " + webDownloadItem.getGuid());
          resolve()
        })
        this.controller.setDownloadDelegate(this.delegate);
      } catch (error) {
        console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
        reject()
      }
    })
  }

最后,复制沙箱中的文件到本地Download目录中

ts 复制代码
 copyToDownload(fileName:string,fullPath:string){
    // 文件选择器配置
    const context = getContext(this) as common.UIAbilityContext;
    const documentViewPicker = new picker.DocumentViewPicker(context);
    const documentSaveOptions = new picker.DocumentSaveOptions();

    documentSaveOptions.newFileNames = [fileName]; // 设置默认文件名
    documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD;

    // 打开文件选择器
    const uris = await documentViewPicker.save(documentSaveOptions);
    if (uris.length > 0) {
      const targetDir = new fileUri.FileUri(uris[0]).path;
      const targetUri = `${targetDir}/${fileName}`;
      // 复制到Download下
      const sourceStats = fs.statSync(fullPath);
      if (sourceStats.isFile()) {
        try {
          fs.copyFileSync(fullPath, targetUri);
          console.info(`文件已保存至:${targetUri}`);
          ToastUtil.showToast('下载成功:' + targetUri)
          // 删除临时文件
          fs.unlinkSync(fullPath);
        } catch (e) {
          console.error('文件复制失败' + e)
          ToastUtil.showToast('下载失败')
        }
      }
    }
 }

通过这种方式,就可以实现pdf的下载和保存,并且无需声明额外的权限。

相关推荐
前端不太难28 分钟前
HarmonyOS 游戏项目,从 Demo 到可上线要跨过哪些坑
游戏·状态模式·harmonyos
全栈探索者1 小时前
列表渲染不用 map,用 ForEach!—— React 开发者的鸿蒙入门指南(第 4 期)
react.js·harmonyos·arkts·foreach·列表渲染
一只大侠的侠2 小时前
Flutter开源鸿蒙跨平台训练营 Day8获取轮播图网络数据并实现展示
flutter·开源·harmonyos
Lionel6893 小时前
鸿蒙Flutter跨平台开发:首页特惠推荐模块的实现
华为·harmonyos
盐焗西兰花3 小时前
鸿蒙学习实战之路-Reader Kit自定义页面背景最佳实践
学习·华为·harmonyos
果粒蹬i3 小时前
【HarmonyOS】DAY10:React Native开发应用品质升级:响应式布局与用户体验优化实践
华为·harmonyos·ux
早點睡3904 小时前
基础入门 React Native 鸿蒙跨平台开发:react-native-flash-message 消息提示三方库适配
react native·react.js·harmonyos
早點睡3904 小时前
高级进阶 ReactNative for Harmony项目鸿蒙化三方库集成实战:react-native-image-picker(打开手机相册)
react native·react.js·harmonyos
早點睡3904 小时前
基础入门 React Native 鸿蒙跨平台开发:react-native-easy-toast三方库适配
react native·react.js·harmonyos
前端不太难5 小时前
在 HarmonyOS 上,游戏状态该怎么“死而复生”
游戏·状态模式·harmonyos