Skip to content
Guides

PDF to Image Conversion

This sample shows how to convert PDF to image.

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

// PDF to picture and save the picture
- (void)PDFToImage:(CPDFDocument *)document {
  NSString *commandLineStr = @""  
  
    // Get Sandbox path for saving the PDFFile
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *writeDirectoryPath = [NSString stringWithFormat:@"%@/%@", path, @"PDFToImage"];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:writeDirectoryPath])
        [[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:writeDirectoryPath] withIntermediateDirectories:YES attributes:nil error:nil];
    
    // Traverse the page, converting all pages to images
    for (int i = 0; i < document.pageCount; i++) {
        // Get image from page
        CPDFPage *page = [document pageAtIndex:i];
        CGSize pageSize = [document pageSizeAtIndex:i];
        UIImage *image = [page thumbnailOfSize:pageSize];
        
        // Save image in Sandbox
        NSString *imageFilePath = [writeDirectoryPath stringByAppendingFormat:@"/PDFToImageTest%d.png", i];
        [self.imageFilePaths addObject:imageFilePath];
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
        BOOL success = [imageData writeToFile:imageFilePath atomically:YES];
        
        if (success) {
            commandLineStr = [self.commandLineStr stringByAppendingString:@"Done.\n"];
            commandLineStr = [self.commandLineStr stringByAppendingFormat:@"Done. Results saved in PDFToImageTest%d.png\n", i];
        } else {
            commandLineStr = [self.commandLineStr stringByAppendingString:@"Done.\n"];
            commandLineStr = [self.commandLineStr stringByAppendingFormat:@"Done. Results saved in PDFToImageTest%d.png fail !\n", i];
        }
    }
}