目录

Opening and Saving a PDF Document

Before performing operations such as adding content, header and footer, watermark, background image, or bookmark on a PDF document, you need to open the document. After the operations are complete, you need to save the PDF document.

Both pdfService and PdfView can be used to open and save documents, while they have differences in the application scenarios:

API Description

API Name Description
loadDocument(path: string, password?: string, onProgress?: (progress: number) => number): ParseResult Loads the document with the specified document path.
saveDocument(path: string, onProgress?: (progress: number) => number): boolean Saves a document.

Sample Code

  1. Call the loadDocument method to load a PDF document.

  2. Call the saveDocument method in the Save As and Save buttons to save the document as a PDF document and overwrite the source PDF document.

import { pdfService } from '@kit.PDFKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { fileIo } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...

@Entry
@Component
struct OpenDocument {
  private pdfDocument: pdfService.PdfDocument = new pdfService.PdfDocument();
  private context = this.getUIContext().getHostContext() as Context;
  private filePath = '';
  @State saveEnable: boolean = false;

  aboutToAppear(): void {
    this.filePath = this.context.filesDir + '/input.pdf';
    try {
      let res = fileIo.accessSync(this.filePath);
      if(!res) {
        // Ensure that the input.pdf document exists in the src/main/resources/resfile project directory.
        let content: Uint8Array = this.context.resourceManager.getRawFileContentSync('resfile/input.pdf');
        let fdSand =
          fileIo.openSync(this.filePath, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE | fileIo.OpenMode.TRUNC);
        fileIo.writeSync(fdSand.fd, content.buffer);
        fileIo.closeSync(fdSand.fd);
      }
      this.pdfDocument.loadDocument(this.filePath);
    } catch (e) {
      let error: BusinessError = e as BusinessError;
      hilog.error(0x0000, 'OpenDocument', `Failed to loadDocument. Code: ${error.code}, message: ${error.message} `);
    }
  }

  build() {
    Column() {
      Row() {
      // ...
        Button('Save As').onClick(() => {
          let outPdfPath = this.context.filesDir + '/testSaveAsPdf.pdf';
          let result = this.pdfDocument.saveDocument(outPdfPath);
          this.saveEnable = true;
          hilog.info(0x0000, 'OpenSavePage', 'saveAsPdf %{public}s!', result ? 'success' : 'fail');
        })
        Button('Save').enabled(this.saveEnable).onClick(() => {
          // Add headers, footers, watermarks, or background images to the PDF document, and save the document.
          let tempDir = this.context.tempDir;
          let tempFilePath = tempDir + `/temp${Math.random()}.pdf`;
          try {
            fileIo.copyFileSync(this.filePath, tempFilePath);
          } catch (e) {
            let error: BusinessError = e as BusinessError;
            hilog.error(0x0000, 'OpenSavePage', `Failed to copyFileSync. Code: ${error.code}, message: ${error.message} `);
          }
          let pdfDocument: pdfService.PdfDocument = new pdfService.PdfDocument();
          // Load the temporary document.
          let loadResult = pdfDocument.loadDocument(tempFilePath, '');
          if (loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
            let result = pdfDocument.saveDocument(this.filePath);
            hilog.info(0x0000, 'OpenSavePage', 'savePdf %{public}s!', result ? 'success' : 'fail');
          }
        })
      }
    }
  }
}