目录

Opening and Saving a PDF Document

Use Cases

Loads a PDF document from a local path to preview the PDF document. You can save a PDF document that contains annotations.

The capabilities are the same as those of pdfService. For details about the differences, see the use cases of Opening and Saving a PDF Document of pdfService.

API Description

API Name Description
loadDocument(path: string, password?: string, initPageIndex?: number, onProgress?: Callback<number>): Promise<pdfService.ParseResult> Loads a PDF document.
saveDocument(path: string, onProgress?: Callback<number>): Promise<number> Saves a PDF document. This API uses a promise to return the result.

Sample Code

  1. Load the PDF document in the aboutToAppear function.

  2. Call the PdfView preview component to render the display.

  3. Call the saveDocument method via the savePdfDocument button to save the PDF document as a new one.

import { pdfService, PdfView, pdfViewManager } from '@kit.PDFKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
 // ...

@Entry
@Component
struct PdfOpenDocument {
  private controller: pdfViewManager.PdfController = new pdfViewManager.PdfController();
  private context = this.getUIContext().getHostContext() as Context;
  private loadResult: pdfService.ParseResult = pdfService.ParseResult.PARSE_ERROR_FORMAT;

  aboutToAppear(): void {
    // Ensure that the input.pdf document exists in the src/main/resources/resfile project directory.
    let filePath = this.context.resourceDir + '/input.pdf';
    (async () => {
      this.loadResult = await this.controller.loadDocument(filePath);
    })()
  }

  build() {
   // ...
      Column() {
        Button('savePdfDocument').onClick(async () => {
          if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
            let savePath = this.context.filesDir + '/savePdfDocument.pdf';
            let result = await this.controller.saveDocument(savePath);
            hilog.info(0x0000, 'PdfPage', 'savePdfDocument %{public}s!', result ? 'success' : 'fail');
          }
        })
        PdfView({
          controller: this.controller,
          pageFit: pdfService.PageFit.FIT_WIDTH,
          showScroll: true
        })
          .id('pdfview_app_view')
          .layoutWeight(1);
      }
      // ...
    .width('100%')
    .height('100%')
  }
}