2012-01-12 9 views

Trả lời

10

Nếu bạn có UIImageView vào UIViewController sau đó gọi phương pháp này:

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

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

    return pdfData; 
} 

Sử dụng như thế này:

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

Nó không phải là rất khó, nhưng có một vài bước để thiết lập tất cả mọi thứ lên. Về cơ bản, bạn cần phải tạo ra một bối cảnh đồ họa PDF, và sau đó vẽ vào nó với các lệnh vẽ tiêu chuẩn. Để chỉ cần đặt một UIImage thành một file PDF, bạn có thể làm một cái gì đó như sau:

// 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(); 

Để biết thêm thông tin, vui lòng xem Drawing and Printing Guide for iOS.