Skip to content

Instantly share code, notes, and snippets.

@brandonbeecroft
Created March 31, 2015 20:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonbeecroft/cbffb44f47cc409ed981 to your computer and use it in GitHub Desktop.
Save brandonbeecroft/cbffb44f47cc409ed981 to your computer and use it in GitHub Desktop.
// properties
@property (strong, nonatomic) IBOutlet UIView *PDFView;
@property (weak, nonatomic) IBOutlet UIView *displayView;
@property (nonatomic, strong) NSData *pdf;
// I have a button on the story board to generate a PDF
// it calls this function
-(IBAction)createAndSendPDF {
self.PDFView.hidden = NO;
self.displayView.hidden = YES;
self.pdf = [self generatePDF];
[self emailPDF:self.pdf];
}
//generate the PDF. This function takes the view created in storyboard (self.PDFview)and creates the graphic context needed for a PDF
- (NSData*)generatePDF {
NSMutableData * pdfData=[NSMutableData data];
// by default, the UIKit will create a 612x792 page size (8.5 x 11 inches)
// if you pass in CGRectZero for the size
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);
CGContextRef pdfContext=UIGraphicsGetCurrentContext();
UIGraphicsBeginPDFPage();
// use the currently being outputed view's layer here
[self.PDFView.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
self.displayView.hidden = NO;
self.PDFView.hidden = YES;
return pdfData;
}
// for clarity, here is my email function
- (void)emailPDF:(NSData*)pdfData {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:@"Kiddo PDF"];
[picker addAttachmentData:pdfData mimeType:@"application/pdf"
fileName:[NSString stringWithFormat:@"Kiddo.pdf"]];
[picker setMessageBody:@"Here's the Kiddo PDF you wanted." isHTML:YES];
[self presentViewController:picker animated:YES completion:nil];
}
@brandonbeecroft
Copy link
Author

Layout your view in code or storyboard and this code will take that view and generate a pdf.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment