2012-01-12 23 views
6

我在我的UIViewController中有一个UIImage,我想将该图像迁移到PDF格式的合成文件,因此可以进行这种迁移吗?请指导我我不知道这一点。如何从UIImage制作PDF?

回答

10

如果你的UIImageView到UIViewController中再调用这个方法:

-(NSData*)makePDFfromView:(UIView*)view 
{ 
    NSMutableData *pdfData = [NSMutableData data]; 

    UIGraphicsBeginPDFContextToData(pdfData, view.bounds, nil); 
    UIGraphicsBeginPDFPage(); 
    CGContextRef pdfContext = UIGraphicsGetCurrentContext(); 
    [view.layer renderInContext:pdfContext]; 
    UIGraphicsEndPDFContext(); 

    return pdfData; 
} 

使用这样的:

NSData *pdfData = [self makePDFfromView:imgView]; 
//[pdfData writeToFile:@"myPdf.pdf" atomically:YES]; - save it to a file 
9

这不是很难,但有几个步骤来设置一切。基本上,您需要创建一个PDF图形上下文,然后使用标准绘图命令进行绘制。为了简单地把一个UIImage的转换成PDF,你可以这样做以下:

// assume this exists and is in some writable place, like Documents 
NSString* pdfFilename = /* some pathname */ 

// Create the PDF context 
UIGraphicsBeginPDFContextToFile(pdfFilename, CGRectZero, nil); // default page size 
UIGraphicsBeginPDFPageWithInfo(CGRectZero, nil); 

// Draw the UIImage -- I think PDF contexts are flipped, so you may have to 
// set a transform -- see the documentation link below if your image draws 
// upside down 
[theImage drawAtPoint:CGPointZero]; 

// Ending the context will automatically save the PDF file to the filename 
UIGraphicsEndPDFContext(); 

欲了解更多信息,请参阅Drawing and Printing Guide for iOS