2012-01-12 30 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