我如何从UIImage制作Pdf?

时间:2012-01-12 15:37:20

标签: ios pdf uiimage

我的UIViewController中有一个UIImage,我想将该图像迁移到PDF格式,所以有可能进行这种迁移吗?请指导我,我不知道这个。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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