Frequently Asked Question

Convert PDF to images and bitmaps (iOS)
Last Updated 11 months ago

This code shows how to convert all the pages from a PDF file in respective bitmaps on iOS devices.

/**
 * converts the given document into images.
 *
 * @param filePath the input document's path
 * @param password the document's password (if-any)
 * @param savePath the path to save the images into
 * @param size the largest side(width or height), to be used to calculate the image size (0 to use original pdf's dimension)
 * @param startIndex the index (0 to page count - 1) of the first page to generate.
 * @param endIndex the index (0 to page count - 1 inclusive) of the last page to generate.
 * @param type the type of the generated image, 0: jpeg, otherwise:png
 * @return 0: for success
 *        -1:need input password
 *        -2:unknown encryption
 *        -3:damaged or invalid format
 *        -4:unsatisfied link error
 *        -10:access denied or invalid file path
 *        others:unknown error
 */

- (int)pdf2image:(NSString *)filePath :(NSString *)password :(NSString *)savePath :(int)size :(int)startIndex :(int)endIndex :(int)type
{
    int result = 0;
    Global_setAnnotTransparency(0);    
    PDFDoc *document = [[PDFDoc alloc] init];
    result = [document open:filePath :password];   
    if (result == 0) { // Success
        int numOfPages = document.pageCount;
            if (startIndex < 0 || startIndex >= numOfPages) startIndex = 0;
            if (endIndex <= 0 || endIndex >= numOfPages) endIndex = numOfPages - 1;

            NSString *mFileName = [[filePath lastPathComponent] stringByDeletingPathExtension];

            //generate thumbnails
            for(int i = startIndex; i <= endIndex; i++) {
                NSLog(@"---- start page: %i ----", i);
                @autoreleasepool {
                    float pageWidth = [document pageWidth:i];
                    float pageHeight = [document pageHeight:i];
                    int imageWidth, imageHeight = 0;           
                    if (pageWidth > pageHeight) { //Set the given size, original size otherwise
                        imageWidth = (size == 0) ? pageWidth : size;
                        imageHeight = (pageHeight * imageWidth / pageHeight);
                    } else {
                        imageHeight = (size == 0) ? pageHeight : size;
                        imageWidth = (pageWidth * imageHeight / pageHeight);
                    }

                    float ratio = imageWidth / pageWidth;
                    float ratioy = imageHeight / pageHeight;
                    if( ratio > ratioy ) ratio = ratioy;                                

                    imageWidth = pageWidth * ratio;
                    imageHeight = pageHeight * ratio;                                                    PDFPage *page = [document page:i];
                    if (page != nil) {
                        PDFDIB *bitmap = [[PDFDIB alloc] init:imageWidth :imageHeight];
                        PDFMatrix *mat = [[PDFMatrix alloc] init:ratio :-ratio :(imageWidth - pageWidth * ratio) / 2 :(imageHeight + pageHeight * ratio) / 2];
                        [page renderPrepare:nil];
                        
                        if ([page render:bitmap :mat :1]) {
                            NSString *outputPath = [[savePath stringByAppendingPathComponent:mFileName] stringByAppendingFormat:@"_%i", i];
                            outputPath = [outputPath stringByAppendingPathExtension:(type == 0) ? @"jpeg" : @"png"];
                            void *data = [bitmap data];                   
                            CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, data, imageWidth * imageHeight * 4, NULL);
    
                            CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
                            CGImageRef imgRef = CGImageCreate(imageWidth, imageHeight, 8, 32, imageWidth<<2, cs, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst, provider, NULL, FALSE, kCGRenderingIntentDefault);                                                
                            CGContextRef context = CGBitmapContextCreate(NULL, imageWidth * 1, imageHeight * 1, 8, 0, cs, kCGImageAlphaPremultipliedLast);

                        // Draw                                                                        CGContextSetAlpha(context, 1);                        

                        CGContextSetRGBFillColor(context, (CGFloat)0.0, (CGFloat)0.0, (CGFloat)0.0, (CGFloat)1.0 );
                        CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), imgRef);                        

                        // Get your image
                        CGImageRef cgImage = CGBitmapContextCreateImage(context);
                        CGColorSpaceRelease(cs)
                        CGDataProviderRelease(provider);                        
                        NSLog(@"---- write page: %i ----", i);                        

                        if (type == 0) {
                            [[NSFileManager defaultManager] createFileAtPath:outputPath contents:UIImageJPEGRepresentation([UIImage imageWithCGImage:cgImage], 0.9) attributes:nil];
                        } else {
                            [[NSFileManager defaultManager] createFileAtPath:outputPath contents:UIImagePNGRepresentation([UIImage imageWithCGImage:cgImage]) attributes:nil];
                        }
                    }
                    page = nil;
                }
            }
        }        
        document = nil;
    }    
    return result;
}

Loading ...