How do I create a UIImage using PDFDraw without writing to disk?

Q: I’m using iOS. How do I create a UIImage using PDFDraw without writing to disk?

A: The following code snippet shows how to use PDFDraw to create a UIImage of the first page of a PDFDoc:

PDFDoc* doc = [[PDFDoc alloc] initWithFilepath:file];
Page* page = [doc GetPage:1];
PDFDraw* draw = [[PDFDraw alloc] initWithDpi:dpi];
BitmapInfo* bitmapInfoObject;

bitmapInfoObject = [draw GetBitmap:page pix_fmt:e_bgra demult:NO];
@catch (NSException* ex)
NSLog(@“PDFNet could not render.”);

NSData* data = [bitmapInfoObject GetBuffer];
unsigned char* test = calloc(sizeof(unsigned char)[bitmapInfoObject getWidth][bitmapInfoObject getHeight], sizeof(unsigned char));
[data getBytes:test length:sizeof(unsigned char)[bitmapInfoObject getWidth][bitmapInfoObject getHeight]];
UIImage* testImage = imageFromRawBGRAData(data, [bitmapInfoObject getWidth], [bitmapInfoObject getHeight], YES);

Where the method imageFromRawBGRAData is:

UIImage* imageFromRawBGRAData(NSData* data, int width, int height, bool retinaEnabled)
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
const int bitsPerComponent = 8;
const int bitsPerPixel = 4 * bitsPerComponent;
const int bytesPerRow = 4 * width;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

CGImageRef imageRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);

double screenScale = 1;

if (retinaEnabled && [[UIScreen mainScreen] respondsToSelector:@selector(scale)] == YES)
screenScale = [[UIScreen mainScreen] scale] ;

UIImage *myImage = [UIImage imageWithCGImage:imageRef scale:screenScale orientation:UIImageOrientationUp];


return myImage;