Question

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.

Was it helpful?

Solution

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);

OTHER TIPS

Here is what you do :

   NSMutableData *pdfData = [[NSMutableData alloc] init];
   CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData);
   const CGRect mediaBox = CGRectMake(0.0f, 0.0f, drawingWidth, drawingHeight);
   CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &mediaBox, NULL);

   UIGraphicsPushContext(pdfContext);
   CGContextBeginPage(pdfContext, &mediaBox);

   CGContextDrawPDFPage(pdfcontext, pdfPage);

   CGContextEndPage(pdfContext);    
   CGPDFContextClose(pdfContext);
   UIGraphicsPopContext();

   CGContextRelease(pdfContext);
   CGDataConsumerRelease(dataConsumer);

  // Mail part
  MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
  mailViewController.mailComposeDelegate = self;
  NSString *mime=@"application/pdf";            
  [mailViewController setSubject:@"Subject"];
  [mailViewController setMessageBody:@"Message Body" isHTML:NO];
  [mailViewController addAttachmentData:[pdfData copy] mimeType:mime fileName:@"page.pdf"];
  [self presentModalViewController:mailViewController animated:YES];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top