PDFium Delphi Component 文件

FindFirst 方法

元件: TPdf  ·  單元: PDFium
開始搜尋指定文字。StartIndex 為 0 起算,-1 代表頁面結尾。DirectionUp 參數決定這次搜尋的方向

Syntax

function FindFirst(const Text: WString; Options: TSearchOptions = []; StartIndex: Integer = 0; DirectionUp: Boolean = True): Integer;

TextWString。要在目前頁面上搜尋的 Unicode 文字字串
OptionsTSearchOptions。一組控制比對行為的 TSearchOption 旗標。支援的旗標有 soMatchCase(區分大小寫比對)與 soMatchWholeWord(僅全字比對)。傳入 [] 可進行不區分大小寫的子字串搜尋
StartIndexInteger。搜尋開始位置的字元索引,以 0 為基底。傳入 -1 可從頁面最後一個字元開始(當 DirectionUp 為 False 時很有用)。預設值為 0
DirectionUpBoolean。決定初始搜尋方向。True(預設)從 StartIndex 向頁面結尾搜尋;False 向頁面開頭搜尋。後續的 FindNext 呼叫一律向前移動;FindPrevious 一律向後移動

Return Value

第一個相符項目的字元索引(以 0 為基底),找不到相符項目時傳回 -1。內部搜尋控制代碼會保留下來,讓後續的 FindNext 或 FindPrevious 呼叫能在不需重新初始化的情況下繼續搜尋

Description

FindFirst 會在目前載入的 PDF 頁面上起始全文搜尋。它接受 Unicode 搜尋字串,以及選用的比對旗標、起始字元位置和方向提示。成功時傳回第一個相符項目的字元索引(以 0 為基底),並儲存內部搜尋控制代碼供後續 FindNext 與 FindPrevious 呼叫重複使用。找不到文字時傳回 -1

StartIndex 參數讓您可以從任意字元位置開始搜尋,而不必一律從頁面頂端開始。傳入 0(預設值)從第一個字元開始,或傳入 -1 錨定在最後一個字元 — 以 DirectionUp = False 進行反向搜尋時特別方便

使用 Options 參數可微調比對行為。soMatchCase 啟用區分大小寫的比較;soMatchWholeWord 將相符範圍限制為完整單字。兩個旗標可合併使用。傳入空集合 [] 則執行不區分大小寫的子字串搜尋

找到相符項目後,以傳回的索引和已知的相符長度呼叫 RectangleCount,即可取得相符文字在頁面上的週框矩形 — 適合用來在檢視器中高亮搜尋結果

Example

var
  Idx, MatchLen, R, I: Integer;
  Rect: TPdfRectangle;
begin
  Pdf1.PageIndex := 0;
  MatchLen := Length('invoice');
  Idx := Pdf1.FindFirst('invoice', [], 0, True);
  while Idx >= 0 do
  begin
    // Retrieve bounding rectangles for the matched text
    R := Pdf1.RectangleCount(Idx, MatchLen);
    for I := 0 to R - 1 do
    begin
      Rect := Pdf1.Rectangle[I];
      Memo1.Lines.Add(Format('Match at char %d, rect [%.1f,%.1f,%.1f,%.1f]',
        [Idx, Rect.Left, Rect.Top, Rect.Right, Rect.Bottom]));
    end;
    Idx := Pdf1.FindNext;
  end;
end;

See Also

FindNext, FindPrevious, Find, CharacterIndexAtPos, CharacterCount, RectangleCount, Text