我是Objective C的新手,所以请帮帮我。
我有一个包含多个标签和文本视图的视图。我正在尝试为该页面/视图生成PDF文件并附加到电子邮件中。
首先,我尝试了这种方法,似乎文件未创建或未附加到电子邮件中。这是我的代码:
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];
由于这不起作用,我首先单独创建PDF,然后将其附加到电子邮件中,尝试了不同的方法。然后我看到PDF文件是在该目录下创建的,但它是空的!!!
以下是我修改后的代码:
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];
我尝试了几种方法,但无法弄清楚我做错了什么。非常感谢!!!
答案 0 :(得分:3)
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];
注意: 不知道draw rect是否适用于views。对我来说它不起作用! 无需将数据写入文件。您可以在邮件组成
时直接执行此操作[mailComposer addAttachmentData:pdfData mimeType:@"pdf" fileName:@"file.pdf"];
试试这个.mime类型只需要字符串pdf。还包括文件名file.pdf的扩展名。
快乐的编码:)