目录

Searching for Keywords

When previewing a PDF document, you can search for keywords (English character case insensitivity) on the page and highlight them. In addition, you can use the setSearchIndex method to highlight the specified search results.

You can use the getSearchIndex method to obtain the highlight index, and use the clearSearch method to clear all search results.

API Description

API Name Description
searchKey(text: string, listener: Callback<number>): void Searches for text and returns the total number of matches.
clearSearch(): void Cancels the highlight of the matched text. This operation is equivalent to searching for empty strings.
setSearchIndex(index: number): void Sets the index of the matching search result. The page will jump to the corresponding search result.
getSearchIndex(): number Obtains the index of the search result that matches the keyword. The default index after the search API is executed is 0.

Sample Code

  1. Load the PDF document.

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

  3. Call the searchKey method via the searchKey button to search for a specified keyword.

  4. Click the previous or next search button to go to the corresponding result.

  5. Call the getSearchIndex method via the getSearchIndex button to obtain the current search result index.

  6. Call the clearSearch method via the clearSearch button to clear the search results.

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

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

  aboutToAppear(): void {
    let dir: string = this.context.resourceDir;
    // Ensure that the input.pdf document exists in the src/main/resources/resfile project directory.
    let filePath: string = dir + '/input.pdf';
    try {
      let res = fileIo.accessSync(filePath);
      if (!res) {
        let content: Uint8Array = this.context.resourceManager.getRawFileContentSync('resfile/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);
      }
    } catch (e) {
      let error: BusinessError = e as BusinessError;
      hilog.error(0x0000, 'SearchPage', `Code: ${error.code}, message: ${error.message} `);
    }
    (async () => {
      this.loadResult = await this.controller.loadDocument(filePath);
    })()
  }

  build() {
    Stack({ alignContent: Alignment.TopStart }) {

      Column() {
        Flex({ wrap: FlexWrap.Wrap, justifyContent: FlexAlign.Start }) {
          Button('searchKey').onClick(async () => {
            if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
              this.controller.searchKey('PDF', (index: number) => {
                this.charCount = index;
                hilog.info(0x0000, 'SearchPage', 'searchKey %{public}s!', index + '');
              })
            }
          })
            .flexShrink(0)
          Button('setSearchPrevIndex').onClick(async () => {
            if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
              if (this.searchIndex > 0) {
                this.controller.setSearchIndex(--this.searchIndex);
              }
            }
          })
            .flexShrink(0)
          Button('setSearchNextIndex').onClick(async () => {
            if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
              if (this.searchIndex < this.charCount) {
                this.controller.setSearchIndex(++this.searchIndex);
              }
            }
          })
            .flexShrink(0)
          Button('getSearchIndex').onClick(async () => {
            if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
              let curSearchIndex = this.controller.getSearchIndex();
              hilog.info(0x0000, 'SearchPage', 'curSearchIndex %{public}s!', curSearchIndex + '');
            }
          })
            .flexShrink(0)
          Button('clearSearch').onClick(async () => {
            if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
              this.controller.clearSearch();
            }
          })
            .flexShrink(0)
        }
        .margin({ top: 50, bottom: 10 })
        .padding({ left: 10, right: 10 })
        PdfView({
          controller: this.controller,
          pageFit: pdfService.PageFit.FIT_WIDTH,
          showScroll: true
        })
          .id('pdfview_app_view')
          .layoutWeight(1);
      }
      // ...
    }
    .width('100%').height('100%')
  }
}