简体   繁体   中英

how to convert a selected image from iphone library to pdf in ios sdk

Now i am using this code. Pdf is generating but image is not displaying.

-(void)imagePickerController:(UIImagePickerController *)pickerdidFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"%@",info);    
    //selectedImage =  [info objectForKey:UIImagePickerControllerOriginalImage];        
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];        
    NSLog(@" selected image is - %@",image);
    imageStr=[NSString stringWithFormat:@"%@",image]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *localFilePath=[documentsDirectory stringByAppendingPathComponent:@"images.pdf"];
    NSLog(@"file path is %@",localFilePath);
    [self pdfGenerate:localFilePath];
    UIGraphicsEndPDFContext();
    [imagePicker dismissViewControllerAnimated:YES completion:nil];
}

-(void)pdfGenerate:(NSString *)filepath
{
    UIGraphicsBeginPDFContextToFile(filepath, CGRectZero, nil);
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 300, 300), nil);
    [self convertImageToPdf];
}

-(void)convertImageToPdf
{
    CGRect imagerect=CGRectMake(0, 0, 300, 300);
    NSLog(@"image  is %@",imageStr);
    UIImage *image=[UIImage imageNamed:imageStr];
    [image drawInRect:imagerect];
}

You are saving the selected image in NSString object imageStr (imageStr=[NSString stringWithFormat:@"%@",image];)

So when you are creating the image inside convertImageToPdf method (UIImage *image=[UIImage imageNamed:imageStr];), your image object is nil . so the pdf is blank.

Instead you can have UIImage reference to the image you picked from the picker. Use that reference inside convertImageToPdf to draw.

Update to your code:

Inside didFinishPickingMediaWithInfo

pickedImage=[info objectForKey:UIImagePickerControllerOriginalImage];        

Inside convertImageToPdf

CGRect imagerect=CGRectMake(0, 0, 300, 300);
[pickedImage drawInRect:imagerect];

pickedImage is an object of type UIImage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM