如何将选定的图像从iphone库转换为ios sdk中的pdf

时间:2013-09-04 06:51:26

标签: iphone ios cgcontext

现在我正在使用此代码。 Pdf正在生成但图像未显示。

-(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];
}

1 个答案:

答案 0 :(得分:0)

您正在NSString对象imageStr中保存所选图像(imageStr = [NSString stringWithFormat:@“%@”,image];)

因此,当您在convertImageToPdf方法(UIImage * image = [UIImage imageNamed:imageStr];)中创建图像时,您的图像对象为nil。所以pdf是空白的。

相反,您可以对从拾取器中拾取的图像进行UIImage引用。在convertImageToPdf中使用该引用来绘制。

更新您的代码:

内部didFinishPickingMediaWithInfo

pickedImage=[info objectForKey:UIImagePickerControllerOriginalImage];        

内部convertImageToPdf

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

pickedImage是UIImage类型的对象。