Guides
Search Text in PDF
This sample shows how to do a full document search and highlight for keywords
objective-c
// Init Methods
- (instancetype)initWithDocument:(CPDFDocument *)document {
CPDFDocument *myDocument = document;
[self searchText:myDocument];
}
// Search text
- (void)searchText:(CPDFDocument *)oldDocument {
NSString *commandLineStr = @""
// Get Sandbox path for saving the PDFFile
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *writeDirectoryPath = [NSString stringWithFormat:@"%@/%@", path, @"TextSearch"];
if (![[NSFileManager defaultManager] fileExistsAtPath:writeDirectoryPath])
[[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:writeDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil];
NSString *writeFilePath = [NSString stringWithFormat:@"%@/%@.pdf",writeDirectoryPath,@"TextSearchTest"];
// Save the document in the test PDF file
NSURL *textSearchURL = [NSURL fileURLWithPath:writeFilePath];
[oldDocument writeToURL:textSearchURL];
// Create a new document for test PDF file
CPDFDocument *document = [[CPDFDocument alloc] initWithURL:textSearchURL];
// Get array of search result
NSArray *resultArray = [document findString:@"PDF" withOptions:CPDFSearchCaseInsensitive];
// Get the first page of search resultsGet the first page of search results
NSArray *selections = [resultArray objectAtIndex:0];
commandLineStr = [commandLineStr stringByAppendingFormat:@"the key PDF have %lu results", selections.count];
// Get the first search result on the first page
CPDFSelection *selection = [selections objectAtIndex:0];
// Set text hignlinght
NSMutableArray *quadrilateralPoints = [NSMutableArray array];
CPDFPage *page = [document pageAtIndex:0];
CGRect bounds = selection.bounds;
[quadrilateralPoints addObject:[NSValue valueWithCGPoint:CGPointMake(CGRectGetMinX(bounds), CGRectGetMaxY(bounds))]];
[quadrilateralPoints addObject:[NSValue valueWithCGPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))]];
[quadrilateralPoints addObject:[NSValue valueWithCGPoint:CGPointMake(CGRectGetMinX(bounds), CGRectGetMinY(bounds))]];
[quadrilateralPoints addObject:[NSValue valueWithCGPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMinY(bounds))]];
CPDFMarkupAnnotation *highlight = [[CPDFMarkupAnnotation alloc] initWithDocument:document markupType:CPDFMarkupTypeHighlight];
highlight.color = [UIColor yellowColor];
highlight.quadrilateralPoints = quadrilateralPoints;
[page addAnnotation:highlight];
// Save the text search action in document
[document writeToURL:self.textSearchURL];
commandLineStr = [commandLineStr stringByAppendingString:@"Done.\n"];
commandLineStr = [commandLineStr stringByAppendingString:@"Done. Results saved in TextSearchTest.pdf\n"];
}