I have a view with several labels and text views. I am trying to generate a PDF file for that page/view and attach to an email.
First, I tried this approach and it seems either the file is not created or not attached to the email. Here are my codes:
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, self.view.bounds, nil);
UIGraphicsBeginPDFPage();
[self.view drawRect:self.view.bounds];
UIGraphicsEndPDFContext();
MFMailComposeViewController *mailComposer = [[[MFMailComposeViewController alloc] init] autorelease];
mailComposer.mailComposeDelegate = self;
[pdfData writeToFile:file atomically:YES];
[mailComposer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:file];
[self presentModalViewController:mailComposer animated:YES];
And since that didn't work, I tried a different approach by creating the PDF separately first, then attach it to the email. Then I saw that the PDF file is created at that directory, but it is empty!!!
Here are my revised codes:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingFormat:@"/tempFile.pdf"];
UIGraphicsBeginPDFContextToFile(file, self.view.bounds, nil);
UIGraphicsBeginPDFPage();
[self.view drawRect:self.view.bounds];
UIGraphicsEndPDFContext();
MFMailComposeViewController *mailComposer = [[[MFMailComposeViewController alloc] init] autorelease];
mailComposer.mailComposeDelegate = self;
[pdfData writeToFile:file atomically:YES];
[mailComposer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:file];
[self presentModalViewController:mailComposer animated:YES];
- Can you please help me to successfully create开发者_StackOverflow a PDF from a view, then attach it to the email?
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, self.view.bounds, nil);
UIGraphicsBeginPDFPage();
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndPDFContext();
MFMailComposeViewController *mailComposer = [[[MFMailComposeViewController alloc] init] autorelease];
mailComposer.mailComposeDelegate = self;
[mailComposer addAttachmentData:pdfData mimeType:@"pdf" fileName:@"file.pdf"];
[self presentModalViewController:mailComposer animated:YES];
Note : Don't know the draw rect works for views.For me its not working! No need to write data into a file.you can directly do it while the mail is composed as
[mailComposer addAttachmentData:pdfData mimeType:@"pdf" fileName:@"file.pdf"];
try this .The mime type requires only the string pdf.Also include the extension to the file name file.pdf.
精彩评论