Friday, 6 January 2012

Creating PDF and attached with email in iphone | Objective C



I'm making an application which requires following requirements.
Steps:

1) Capturing a photo from iPhone Camera.
2) Creating PDF.
3) Saving photo in iPhone Library.
4) Email Attachment with PDF.


In .h file


#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

Protocols Used 
<MFMailComposeViewControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

NSString *imagePathString;
IBOutlet UIImageView *imgView;

@property (nonatomic,retain) NSString *imagePathString;
@property (nonatomic,retain) UIImageView *imgView;

-(IBAction) scanningPrescription : (id) sender;
-(IBAction) emailToPharmacist : (id) sender;

//EMAIL_FUNCTIONS
-(void)showPicker;
-(void)displayComposerSheet ;
-(void)launchMailAppOnDevice;


In .m file
#import <QuartzCore/QuartzCore.h>

@synthesize imagePathString,imgView;

- (void)viewDidLoad {

    self.imagePathString = [[NSString alloc]init];
    [super viewDidLoad];
}
-(IBAction) capturingPhoto : (id) sender{

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
// If camera is available

UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.delegate = self;
[self presentModalViewController:imagePicker animated:YES];

}else {
// Camera is not available

UIAlertView *alertMsg = [[UIAlertView alloc] initWithTitle:nil message:@"Functionality is only available on devices with cameras." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertMsg show];
[alertMsg release];


}


}

/*----------------------------DELEGATES_METHOD_FOR_CAMERA-----------------------*/

//CANCEL_CAPTURING
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [self dismissModalViewControllerAnimated:YES];
}

//FINISH_CAPTURING_AN_IMAGE

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

NSLog(@"INFO_DESCRIPTion %@",[info description]);

UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

// You have the image. You can use this to present the image in the next view like you require in #3.
//  Access the uncropped image from info dictionary

// SAVE_IMAGE
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

[picker release];
[self dismissModalViewControllerAnimated:YES];

}

//SAVE_IMAGE

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{

// Unable to save the image
if (error){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
  message:@"Unable to save image to Photo Album."
 delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];

[alert show];
[alert release];

}
else{
// All is well

//Take an ImageView and set capturing image on that.
self.imgView.image=image;


 
    //create the file path to store our PDF document (will be created inside our app's documents directory)
    //If you're using the simulator, the file can be found in: homeFolder/Library/Application Support/iPhone Simulator/versionOfIOS_Simulator/Applications/SomeWeirdStringIdentifyingYourApp/Documents/
 
    NSString *fileName = @"YOUR_PDF_NAME.pdf";
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
NSString *saveFileName = fileName;
//This String used for Saving a Path on which capturing image to be stored.
self.imagePathString = [saveDirectory stringByAppendingPathComponent:saveFileName];
    NSLog(@"%@",self.imagePathString);

}


}


-(IBAction) emailToSomeElse : (id) sender{

[self showPicker];
}

-(void)showPicker
{

Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if (mailClass != nil)
{
// We must always check whether the current device is configured for sending emails
if ([mailClass canSendMail])
{
[self displayComposerSheet];
}
else
{
[self launchMailAppOnDevice];
}
}

}


#pragma mark -
#pragma mark Compose Mail

// Displays an email composition interface inside the application. Populates all the Mail fields.
-(void)displayComposerSheet
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

[picker setSubject:@"SUBJECT"];


// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:@"TO_EMAIL_ADDRESS"];

NSArray *ccRecipients = [[NSArray alloc] init];
NSArray *bccRecipients = [[NSArray alloc] init];

[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];

/*// Attach an image to the email
NSString *path = [[NSBundle mainBundle] pathForResource:@"IMAGE_NAME" ofType:@"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:@"image/png" fileName:@"IMAGE_NAME"];
*/

//PDF_ATTACHMENT
//Take ImageView on View and on UIGraphicsBeginPDFContextToData(passing imageview bounds i.e capturing photo on imageview) and renderInContext method using Quartz framework

NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData,self.imgView.bounds, nil);
UIGraphicsBeginPDFPage();

[self.imgView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIGraphicsEndPDFContext();



[picker addAttachmentData:pdfData mimeType:@"pdf" fileName:@"YOUR_PDF_NAME.pdf"];


// Fill out the email body text
NSString *emailBody = @"Cool!";
[picker setMessageBody:emailBody isHTML:YES];

[self presentModalViewController:picker animated:YES];
    [picker release];
}


// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
//Image View asssign nil after email send successsfully.
self.imgView.image=nil;
//message.hidden = NO;  // Useless

// Notifies users about errors associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:{
//message.text = @"Result: cancelled";
NSString *str =@"Your mail has been cancelled.Try Again!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mail Cancel" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alert show];
[alert release];
break;
}
case MFMailComposeResultSaved:{
//message.text = @"Result: saved";
NSString *str =@"Your Mail has been saved";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mail Saved" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alert show];
[alert release];
break;
}
case MFMailComposeResultSent:{
//message.text = @"Result: sent";
NSString *str =@"Your mail has been sent successfully.Thanks!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mail Sent" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alert show];
[alert release];
break;
}
case MFMailComposeResultFailed:{
//message.text = @"Result: failed";
NSString *str =@"Your mail hase been failed.Try Again!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mail Failed" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alert show];
[alert release];
break;
}
default:{
//message.text = @"Result: not sent";
NSString *str =@"Your Mail has not been sent";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mail Not Sent" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alert show];
[alert release];
break;
}
}
[self dismissModalViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark Workaround

// Launches the Mail application on the device.
-(void)launchMailAppOnDevice
{
NSString *recipients = @"mailto:&subject=";

// FOR TESTING
//NSString *recipients = @"mailto:@""&subject=";
NSString *body = @"&body=";

NSString *email1 = [NSString stringWithFormat:@"%@%@", recipients, body];
email1 = [email1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email1]];
}

No comments:

Post a Comment