How to attach CGPDFDocument/CGPDFPage to MFMailComposeViewController

倾然丶 夕夏残阳落幕 提交于 2019-12-03 23:01:39

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/12637508/how-to-attach-cgpdfdocument-cgpdfpage-to-mfmailcomposeviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!