title: How to search text in pdf document with quartz
body: <p>I'm using quartz to display pdf. I need to get the indexes of pages where my searching text exists. Anyone can help me? Thanks.</p>
  
  <p><strong>Solution:</strong>
  There is a sample of code that extracts a text from the page and check it for the sequences.</p>
  
  <pre><code>#import &lt;Foundation/Foundation.h&gt;
  
  @interface PDFSearcher : NSObject {
      CGPDFOperatorTableRef table;
      NSMutableString *currentData;
  }
  
  @property (nonatomic, retain) NSMutableString * currentData;
  -(id)init;
  -(BOOL)page:(CGPDFPageRef)inPage containsString:(NSString *)inSearchString;
  
  @end
  
  #import "PDFSearcher.h"
  
  @implementation PDFSearcher
  @synthesize currentData;
  void arrayCallback(CGPDFScannerRef inScanner, void *userInfo)
  {
      PDFSearcher * searcher = (PDFSearcher *)userInfo;
  
      CGPDFArrayRef array;
  
      bool success = CGPDFScannerPopArray(inScanner, &amp;array);
  
      for(size_t n = 0; n &lt; CGPDFArrayGetCount(array); n += 2)
      {
          if(n &gt;= CGPDFArrayGetCount(array))
              continue;
  
          CGPDFStringRef string;
          success = CGPDFArrayGetString(array, n, &amp;string);
          if(success)
          {
              NSString *data = (NSString *)CGPDFStringCopyTextString(string);
              [searcher.currentData appendFormat:@"%@", data];
              [data release];
          }
      }
  }
  
  void stringCallback(CGPDFScannerRef inScanner, void *userInfo)
  {
      PDFSearcher *searcher = (PDFSearcher *)userInfo;
  
      CGPDFStringRef string;
  
      bool success = CGPDFScannerPopString(inScanner, &amp;string);
  
      if(success)
      {
          NSString *data = (NSString *)CGPDFStringCopyTextString(string);
          [searcher.currentData appendFormat:@"%@", data];
          [data release];
  
      }
  }
  
  -(id)init
  {
      if(self = [super init])
      {
          table = CGPDFOperatorTableCreate();
          CGPDFOperatorTableSetCallback(table, "TJ", arrayCallback);
          CGPDFOperatorTableSetCallback(table, "Tj", stringCallback);
      }
      return self;
  }
  
  -(BOOL)page:(CGPDFPageRef)inPage containsString:(NSString *)inSearchString
  {
      [self setCurrentData:[NSMutableString string]];
      CGPDFContentStreamRef contentStream = CGPDFContentStreamCreateWithPage(inPage);
      CGPDFScannerRef scanner = CGPDFScannerCreate(contentStream, table, self);
      bool ret = CGPDFScannerScan(scanner);
      CGPDFScannerRelease(scanner);
      CGPDFContentStreamRelease(contentStream);
      //NSLog(@"%u, %@", [self.currentData length], self.currentData);
      return ([[self.currentData uppercaseString] 
               rangeOfString:[inSearchString uppercaseString]].location != NSNotFound);
  }
  @end
  </code></pre>