For some reason, this seems like a difficult thing to google for and can often lead to people doing things the wrong way, so I’ll show how simple it is to do PDF rendering in iOS.
The problem: you have an iPhone or iPad app that does some custom drawing inside a subclass of UIView. Now you want all of your awesome graphics to be exported to a PDF so you can either archive it or share it with people who don’t have your app.
Unfortunately, a lot of people google around for a solution and end up finding some really convoluted examples using CGPDFContextCreateWithURL and making CFDictionaries. While you may be able to come up with a working solution using the CF* and CG* functions, it’s not much more complicated than most people need.
Luckily, UIKit has some very handy helper functions in UIKit for doing exactly this. Assuming you’re insde a subclass of UIView that does rendering in it’s drawRect method, here’s how you generate a PDF called fileName at path:
NSMutableDictionary *pdfDict = [[NSMutableDictionary alloc] init];
[pdfDict setValue:fileName forKey:(NSString*)kCGPDFContextTitle];
[pdfDict setValue:@"Author of the PDF" forKey:(NSString*)kCGPDFContextAuthor];
[pdfDict setValue:@"App that created the PDF" forKey:(NSString*)kCGPDFContextCreator];
UIGraphicsBeginPDFContextToFile(path,
CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height),
pdfDict);
[pdfDict release];
UIGraphicsBeginPDFPage();
[self drawRect:self.bounds];
UIGraphicsEndPDFContext();
It’s that simple. UIGraphicsBeginPDFContextToFile creates a PDF context and sets it as the current UIKit context. Thus, all rendering operations on the current context will be directed to the PDF instead of the screen, until you call UIGraphicsEndPDFContext. The result is a PDF generated with native drawing commands, often much smaller yet better quality than an image capture of the view.
NOTE: If you’re rendering text in your UIView, make sure you use text rendering methods like [@"my string": drawAtPoint:] instead of placing UILabels over the view. The labels won’t be rendered to the PDF.
