I'm trying to take an image that I have in a image object and render into a Core Graphics PDF context-- happens to be on an iPhone but this question surely applies equally to desktop Quartz. This UIImage is a simple color-on-white image at about 600x800 resolution. If I (say) turn it into a PNG file, that file looks exactly as expected-- so the data is OK.
Here's what I'm doing to generate the PDF:
NSMutableData * outputData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)outputData);
CFMutableDictionaryRef attrDictionary = NULL;
attrDictionary = CFDictionaryCreateMutable(NULL, 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(attrDictionary, kCGPDFContextTitle, @"My Awesome Document");
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, NULL, attrDictionary);
CFRelease(dataConsumer);
CFRelease(attrDictionary);
CGImageRef pageImage = [myUIImage CGImage];
CGPDFContextBeginPage(pdfContext, NULL);
CGContextDrawImage(pdfContext, CGRectMake(0, 0, [myUIImage size].width, [myUIImage size].height), pageImage);
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
CGContextRelease(pdfContext);
The resulting PDF, which ends up in outputData
, seems like a valid PDF file (opens correctly, document title is present in metadata), but it consists of precisely one blank page.
What am I doing wrong?
Thanks.
UPDATE: Ha! This was my fault. My test code for just generating the PNG file went through a different path to get the data. The PDF path indeed was receiving an empty image.
I tested your code and it seems to work.
Are you sure your UIImage is valid and not nil when drawing it into the context?
My test method loads a .png from the main bundle and writes the final pdf to a file in the applications document folder:
This issue seems to have been addressed on the iphone dev sdk forums: PDF creation tutorial
All credit goes to danielb21: here is a reprint of their CreatePDFFile method: