【问题标题】:Generate a PDF from a view for emailing从视图生成 PDF 用于发送电子邮件
【发布时间】:2011-02-07 08:48:43
【问题描述】:

我有一个包含多个标签和文本视图的视图。我正在尝试为该页面/视图生成 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];
  • 能否请您帮我从视图中成功创建 PDF,然后将其附加到电子邮件中?

【问题讨论】:

    标签: objective-c pdf-generation


    【解决方案1】:
    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];
    

    注意: 不知道绘图矩形适用于视图。对我来说它不起作用! 无需将数据写入文件。您可以在邮件组成时直接执行此操作

    [mailComposer addAttachmentData:pdfData mimeType:@"pdf" fileName:@"file.pdf"];
    

    试试这个。mime 类型只需要字符串 pdf。还包括文件名 file.pdf 的扩展名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-30
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 2019-09-03
      • 2018-05-06
      相关资源
      最近更新 更多