如何从两个有两页的UIViews创建一个pdf

时间:2013-04-30 15:20:36

标签: ios objective-c pdf uiview

我有两个UIView需要转换为PDF并作为附件发送。我的代码与第一个UIView重叠。 我想将此作为电子邮件的附件发送。

谢谢。

NSMutableData *pdfData=[NSMutableData data];


UIGraphicsBeginPDFContextToData(pdfData,aView.bounds, nil);
CGContextRef pdfContext=UIGraphicsGetCurrentContext();

UIGraphicsBeginPDFPage();
[aView.layer renderInContext:pdfContext];
 UIGraphicsEndPDFContext();


UIGraphicsBeginPDFContextToData(pdfData, bView.bounds, nil);

CGContextRef pdfContext2=UIGraphicsGetCurrentContext();
UIGraphicsBeginPDFPage();

[bView.layer renderInContext:pdfContext2];
  UIGraphicsEndPDFContext();



MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
NSString *subject=[NSString stringWithFormat:@"Delivery Report-%@",[globUserID uppercaseString]];
[mailer setSubject:subject];
[mailer addAttachmentData:pdfData mimeType:@"pdf" fileName:@"DeliveryReport.pdf"];
[self presentModalViewController:mailer animated:YES];

1 个答案:

答案 0 :(得分:12)

不要创建第二个上下文。

NSMutableData *pdfData=[NSMutableData data];
CGRect bounds = CGRectMake(0, 0, 612, 792); // letter sized paper, adjust as needed

UIGraphicsBeginPDFContextToData(pdfData, bounds, nil);
CGContextRef pdfContext = UIGraphicsGetCurrentContext();

UIGraphicsBeginPDFPage();
[aView.layer renderInContext:pdfContext];

UIGraphicsBeginPDFPage();
[bView.layer renderInContext:pdfContext];

UIGraphicsEndPDFContext();