Skip to content
Guides

Extract Text in PDF

This sample shows how to extract all the text of a PDF.

objective-c
// Init Methods
- (instancetype)initWithDocument:(CPDFDocument *)document {
  CPDFDocument *myDocument = document;
  [self extractPageText:myDocument];
    [self extractAllPageText:myDocument];
}

// Extract page text
- (void)extractPageText:(CPDFDocument *)document {
  NSString *commandLineStr = @"";
    commandLineStr = [commandLineStr stringByAppendingString:@"Samples 1: Extract all text content in the specified page\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"Opening the Samples PDF File\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"The text content of the first page of the document:\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"-------------------------------------\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"Text:\n"];
    
  // Extract page text
    CPDFPage *page = [document pageAtIndex:0];
    commandLineStr = [self.commandLineStr stringByAppendingFormat:@"%@\n", page.string];
    
    commandLineStr = [commandLineStr stringByAppendingString:@"\nDone!\n"];
}

// Extract all page text
- (void)extractAllPageText:(CPDFDocument *)document {
    NSString *commandLineStr = @"";
  
    commandLineStr = [commandLineStr stringByAppendingString:@"Samples 1: Extract all text content in the specified page\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"Opening the Samples PDF File\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"The text content of the first page of the document:\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"-------------------------------------\n"];
    commandLineStr = [commandLineStr stringByAppendingString:@"Text:\n"];
    
  // Extract all page text
    for (int i = 0; i < document.pageCount; i++) {
        CPDFPage *page = [document pageAtIndex:i];
        commandLineStr = [commandLineStr stringByAppendingFormat:@"%@\n", page.string];
    }
    
    commandLineStr = [commandLineStr stringByAppendingString:@"\nDone!\n"];
}