1.新建pdf文档预览页面  pdfPreview.ets

import { webview } from '@kit.ArkWeb';

interface RouterParams {
  pdfUrl: string;
}

@Entry
@Component
struct PdfPreview {
  controller: webview.WebviewController = new webview.WebviewController();
  @State currentPdfType: string = "network";
  @State pdfUrl: string = '';
  aboutToAppear() {
    // 接收路由参数
    const params = this.getUIContext().getRouter().getParams() as RouterParams;
    this.pdfUrl = params.pdfUrl;
  }
  build() {
    Column() {
      Web({
        src: this.pdfUrl,  
        controller: this.controller
      })
        .domStorageAccess(true)
        .fileAccess(true)  // 为沙箱访问预留权限
        .width('100%')
        .height('100%')
    }
  }
}

2.调用pdf预览页面

import { router } from '@kit.ArkUI'

@Entry
@Component
struct Login{
  toPdfPreview(url:Resource){
    this.getUIContext().getRouter().pushUrl({
      url: 'pages/Login/pdfPreview',
      params: {
        pdfUrl: url, // 传递的参数
      }
    }, router.RouterMode.Standard, (err) => {
      if (err) {
        console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`);
        return;
      }
    });
  }
  build() {
    Column(){
      Column(){
        //登录页其他布局
      }
      .layoutWeight(1)
      Row({space: 5}){
        Text('登录即代表同意')
          .fontSize(12)
          .fontColor('#999999')
        Text('《用户服务协议》')
          .fontColor('#F28E1B')
          .fontSize(12)
          .onClick(()=>{
            const url = $rawfile('file/userAgreement.pdf')
            this.toPdfPreview(url)
          })
        Text('与')
          .fontColor('#999999')
          .fontSize(12)
        Text('《隐私政策》')
          .fontColor('#F28E1B')
          .fontSize(12)
          .onClick(()=>{
            const url = $rawfile('file/privacyPolicy.pdf')
            this.toPdfPreview(url)
          })
      }
      .margin({bottom:20})
    }
    .height('100%')
    .width('100%')
  }
}

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐