1

In my iPhone application, I have several data items. I want to generate a PDF file using these data items and attach the PDF file in email. What I know, I need to use Quartz 2D to draw the PDF file. Is there any sample code or suggestion about drawing PDF?

rptwsthi
  • 10,094
  • 10
  • 68
  • 109
Shannon
  • 11
  • 1
  • 2
  • 1
    This [Apple Guide](http://developer.apple.com/iphone/library/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_pdf/dq_pdf.html#//apple_ref/doc/uid/TP30001066-CH214-TPXREF101) has a code example of just what you want. – TechZen Dec 08 '09 at 04:47

2 Answers2

3

The following is what I've used to generate an NSData object containing a PDF representation of some Quartz graphics:

NSMutableData *pdfData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData);

const CGRect mediaBox = CGRectMake(0.0f, 0.0f, self.bounds.size.width, self.bounds.size.height);
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &mediaBox, NULL);

UIGraphicsPushContext(pdfContext);

CGContextBeginPage(pdfContext, &mediaBox);

// Your Quartz drawing code goes here   

CGContextEndPage(pdfContext);   
CGPDFContextClose(pdfContext);

UIGraphicsPopContext();

CGContextRelease(pdfContext);
CGDataConsumerRelease(dataConsumer);

You can then save this PDF data to disk or add it as an attachment to your email message, remembering to release it when done.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
1

Here is a good (working) example of the CGPDF functions: http://www.olivetoast.com/blog/hamish/simple_uiscrollview_catiledlayer_example.ot

It uses a CATiledLayer + UIScrollView, this may not be appropriate for a reader of sorts, but it still shows you how to load and draw a PDF doc without UIWebView (which severely restricts your abilities).

Change the layer type back to a layer, add in page handling using CGPDFDocumentGetNumberOfPages and then CGPDFDocumentGetPage and you have a pretty good reader.

I don't know how to perform annotations, I suspect you would need your own data structure on top of the document.

Tristan Warner-Smith
  • 9,631
  • 6
  • 46
  • 75