Q:

How to attach CGPDFDocument/CGPDFPage to MFMailComposeViewController

I have a muti page pdf document stored on local storage. I want to extract any page out of that pdf doc and convert it into NSData to attach it with 'MFMailComposeViewController'. With the following lines of code, I can easily retrive the required page...
CGPDFDocumentRef pdfDoc=CGPDFDocumentCreateWithURL(pdfURL);
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDoc, pageNumber);

But I am unable to find a way to convert pdfPage into NSData so that I can attach it with mail.
NOTE: The requirement is to attach page in PDF format, so please DON'T suggest converting PDF into PNG or JPEG.

A:

CGPDF is primarily for drawing from and to PDF, not for converting PDF data. Therefore, if you want to extract a page, you'll have to draw it. Use for example:
// input
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)inputData);
CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(provider);
CGPDFPageRef page = CGPDFDocumentGetPage(document, pageIndex);
CGRect mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
// output
CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)outputData);
CGContextRef context = CGPDFContextCreate(consumer, &mediaBox, NULL);
// draw
CGContextBeginPage(context, &mediaBox);
CGContextDrawPDFPage(context, page);
CGContextEndPage(context);
// cleanup
CGDataProviderRelease(provider);
CGPDFDocumentRelease(document);
CGDataConsumerRelease(consumer);
CGContextRelease(context);

