Document Library for WinForms
テキスト検索

PDFDocumentSource を使用すると、C1.Win.C1Document 名前空間のメンバである C1TextSearchManager クラスを使用して、検索条件とのマッチングおよびファイルに格納されているすべての単語の検査によるテキスト検索を PDF ファイルに実装できます。このクラスは、検索されるテキストの最初の一致を検索する FindStart、次の一致を検索する FindNext、前の一致を検索する FindPrevious など、さまざまなメソッドを提供します。C1FindTextParams(string text, bool wholeWord, bool matchCase) メソッドを使用して、C1FindTextParams クラスの新しいインスタンスを次のパラメータで初期化できます。

次の図は、PDF ファイルで検索された単語と、検索結果となる一致のリストを示します。

プログラムでテキストを検索するには

このサンプルコードでは、FindStart メソッドを C1TextSearchManager で使用して、検索テキストがある場所を検索します。

手順 1:アプリケーションの設定

  1. C1PdfDocumentSourceOpenFileDialogListView、2 つの TextBox、2 つの Button の各コントロールをフォームに追加します。
  2. ListView を右クリックし、コンテキストメニューから[プロパティ]を選択します。
  3.  プロパティ ウィンドウで、Columns プロパティの隣にある省略符ボタンをクリックし、ColumnHeader コレクションエディタで次の 5 つの列を追加します。
    名前 テキスト
    chnum # 50
    chpage ページ 60
    chbounds 発見位置 100
    chPosInNearText 近いテキスト内の位置 60
    chNearText 近いテキスト 350

  4. [OK]をクリックして、ColumnHeader コレクションエディタを閉じます。
  5. View プロパティに移動し、ドロップダウンリストから Details を選択します。

手順 2:PDF ファイルの参照とテキスト検索

  1. コードビューに切り替えて、次の名前空間を追加します。
    Imports C1.Win.C1Document
    
    using C1.Win.C1Document;
    
  2. プロジェクトに PDF ファイルを追加します。この例では、製品サンプルにある DefaultDocument.pdf という PDF ファイルを使用します。
  3. 次のコードを追加して、C1TextSearchManager クラスのインスタンスを作成し、文字列型の変数 loadedFileを宣言します。
    '検索で使用されるC1TextSearchManagerのインスタンス 
    Dim tsm As C1TextSearchManager
    
    '現在、ロード中のドキュメントの名前
    Dim loadedFile As String = Nothing
    
    // 検索で使用されるC1TextSearchManagerのインスタンス  
    C1TextSearchManager tsm;
    
    // 現在、ロード中のドキュメントの名前
    private string loadedFile = null;
    
  4. 次のコードを InitializeComponent() メソッドの下に追加します。
    'サンプルファイル
    tbFile.Text = Path.GetFullPath("..\..\DefaultDocument.pdf")
    
    'C1TextSearchManagerを作成し、初期化します
    tsm = New C1TextSearchManager(C1PdfDocumentSource1)
    AddHandler tsm.FoundPositionsChanged, AddressOf tsm_FoundPositionsChanged
    
    // サンプルファイル
    tbFile.Text = Path.GetFullPath(@"..\..\DefaultDocument.pdf");
    
    // C1TextSearchManagerを作成し、初期化します
    tsm = new C1TextSearchManager(c1PdfDocumentSource1);
    tsm.FoundPositionsChanged += tsm_FoundPositionsChanged;
    
  5. 次のコードを btnFile のクリックイベントに追加して、PDF ファイルを参照して開くためのダイアログボックスを開きます。
    'ユーザーが検索するPDFファイルを選択できるようにします。
    If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
        tbFile.Text = OpenFileDialog1.FileName
    End If
    
    // ユーザーが検索するPDFファイルを選択できるようにします。
    if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
        tbFile.Text = openFileDialog1.FileName;
    
  6. 次のコードを btnFind のクリックイベントに追加して、テキスト検索を開始します。
    '指定されたPDFファイルをc1PdfDocumentSource1にロードして、検索を実行します。
    Try
        C1PdfDocumentSource1.LoadFromFile(tbFile.Text)
        loadedFile = tbFile.Text
    Catch ex As Exception
        MessageBox.Show(Me, ex.Message, "エラー", MessageBoxButtons.OK,
                        MessageBoxIcon.[Error])
        Return
    End Try
    
    '以前に見つかった位置があれば、それをクリアします。
    ListView1.Items.Clear()
    
    'C1FindTextParamsをユーザが提供する値で初期化します。
    Dim ftp As New C1FindTextParams(tbFind.Text, True, False)
    
    '検索を実行します(FindStartAsyncも利用できます)。
    tsm.FindStart(0, True, ftp)
    
    //指定されたPDFファイルをc1PdfDocumentSource1にロードして、検索を実行します。
    try
    {
        c1PdfDocumentSource1.LoadFromFile(tbFile.Text);
        loadedFile = tbFile.Text;
    }
    catch (Exception ex)
    {
        MessageBox.Show(this, ex.Message, "エラー", MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
        return;
    }
    
    // 以前に見つかった位置があれば、それをクリアします。
    lvFoundPositions.Items.Clear();
    
    // C1FindTextParamsをユーザが提供する値で初期化します。
    C1FindTextParams ftp = new C1FindTextParams(tbFind.Text, true, false);
    
    // 検索を実行します(FindStartAsyncも利用できます)。
    tsm.FindStart(0, true, ftp);
    
  7. 次のイベントを追加して、UI の発見位置のリストを更新します。
    'C1TextSearchManagerのFoundPositionsコレクションが変更されたとき(つまり、
    '検索テキストの新しいインスタンスが見つかったとき)に呼び出されます。
    'これを使用して、UI内で見つかった位置のリストを更新します。
    Private Sub tsm_FoundPositionsChanged(sender As Object, e As EventArgs)
        Dim n As Integer = tsm.FoundPositions.Count
        For i = ListView1.Items.Count To n - 1
            Dim fp As C1FoundPosition = tsm.FoundPositions(i)
            Dim Bounds = fp.GetBounds()
            Dim lvi = New ListViewItem(New String() {(i + 1).ToString(),
                      fp.GetPage().PageNo.ToString(),
                      String.Format("{0}, {1}, {2}, {3}",
                      CInt(Math.Round(Bounds.Left)),
                      CInt(Math.Round(Bounds.Top)),
                      CInt(Math.Round(Bounds.Width)),
                      CInt(Math.Round(Bounds.Height))),
                      fp.PositionInNearText.ToString(),
                      fp.NearText
                      })
            ListView1.Items.Add(lvi)
        Next
    End Sub
    
    // C1TextSearchManagerのFoundPositionsコレクションが変更されたとき(つまり、
    // 検索テキストの新しいインスタンスが見つかったとき)に呼び出されます。
    // これを使用して、UI内で見つかった位置のリストを更新します。
    private void tsm_FoundPositionsChanged(object sender, EventArgs e)
    {
        int n = tsm.FoundPositions.Count;
        for (int i = lvFoundPositions.Items.Count; i < n; i++)
        {
            C1FoundPosition fp = tsm.FoundPositions[i];
            var bounds = fp.GetBounds();
            ListViewItem lvi = new ListViewItem(new string[]
                {
                (i + 1).ToString(),
                fp.GetPage().PageNo.ToString(),
                string.Format("{0}, {1}, {2}, {3}",
                (int)Math.Round(bounds.Left),
                (int)Math.Round(bounds.Top),
                (int)Math.Round(bounds.Width),
                (int)Math.Round(bounds.Height)),
                fp.PositionInNearText.ToString(),
                fp.NearText,
                });
            lvFoundPositions.Items.Add(lvi);
        }
    }
    

手順 3:プロジェクトのビルドおよび実行

  1. [Ctrl]+[Shift]+[B]キーを押してプロジェクトをビルドします。
  2. [F5]キーを押してアプリケーションを実行します。
関連トピック