2009-04-02 5 views

Répondre

2

Cet exemple utilise la bibliothèque inclus avec Adobe Reader et vient de http://www.dotnetspider.com/resources/5040-Get-PDF-Page-Number.aspx:

using Acrobat; 
using AFORMAUTLib;       
private void pdfRandD(string fPath) 
{ 
    AcroPDDocClass objPages = new AcroPDDocClass(); 
    objPages.Open(fPath); 
    long TotalPDFPages = objPages.GetNumPages();    
    objPages.Close(); 
    AcroAVDocClass avDoc = new AcroAVDocClass(); 
    avDoc.Open(fPath, "Title"); 
    IAFormApp formApp = new AFormAppClass(); 
    IFields myFields = (IFields)formApp.Fields;    
    string searchWord = "Search String"; 
    string k = ""; 
    StreamWriter sw = new 
     StreamWriter(@"D:\KCG_FileChecker_Inputs\MAC\pdf\0230_525490_23_cha17.txt", false); 
    for (int p = 0; p < TotalPDFPages; p++) 
    {     
     int numWords = int.Parse(myFields.ExecuteThisJavascript("event.value=this.getPageNumWords(" + p + ");")); 
     k = ""; 
     for (int i = 0; i < numWords; i++) 
     { 
      string chkWord = myFields.ExecuteThisJavascript("event.value=this.getPageNthWord(" + p + "," + i + ", true);"); 
      k = k + " " + chkWord; 
     }     
     if(k.Trim().Contains(searchWord)) 
     { 
      int pNum = int.Parse(myFields.ExecuteThisJavascript("event.value=this.getPageLabel(" + p + ",true);")); 
      sw.WriteLine("The Word " + searchWord + " is exists in " + pNum);      
     } 

    } 
    sw.Close(); 
    MessageBox.Show("Process completed"); 
} 
+1

Merci pour le code! Cependant, cet exemple nécessite une installation d'Adobe Professional. Pour des raisons de redevances, je préférerais avoir un composant pour le faire. – splattne

2

Vous pouvez utiliser Docotic.Pdf library pour rechercher du texte dans des fichiers PDF.

Après l'échantillon montre comment trouver des chaînes spécifiées dans un fichier PDF et les numéros de page correspondants:

static void searchForTextStrings() 
{ 
    string path = ""; 
    string[] stringsToFind = new string[] { }; 

    using (PdfDocument pdf = new PdfDocument(path)) 
    { 
     for (int i = 0; i < pdf.Pages.Count; i++) 
     { 
      string pageText = pdf.Pages[i].GetText(); 
      foreach (string s in stringsToFind) 
      { 
       int index = pageText.IndexOf(s, 0, StringComparison.CurrentCultureIgnoreCase); 
       if (index != -1) 
        Console.WriteLine("'{0}' found on page {1}", s, i); 
      } 
     } 
    } 
} 

Une recherche sensible à la casse peut être réalisée si vous supprimez troisième argument de la méthode IndexOf. Clause de non-responsabilité: Je travaille pour Bit Miracle, vendeur de la bibliothèque.

Questions connexes