如何通过编程方式在iOS中将.png图像转换为.pdf文件

时间:2011-01-27 12:48:13

标签: ios objective-c image pdf

如何将.png格式的图像转换为.pdf文件?

2 个答案:

答案 0 :(得分:0)

使用以下代码从图像创建PDF文件。

UIImage* image = [UIImage imageNamed:@"sample.png"];
CGRect frame = CGRectMake(20, 100, 300, 60);
NSString* fileName = @"FileName.PDF";

NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
                                    NSDocumentDirectory,
                                    NSUserDomainMask,
                                    YES);
NSString *path = [arrayPaths objectAtIndex:0];
NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];
// Create the PDF context using the default page size of 612 x 792.
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);

[image drawInRect:frame];

// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();

答案 1 :(得分:-2)

-(void)createPdf:(NSImage*)image
{  
    PDFDocument *pdf = [[PDFDocument alloc] init];
    NSImage *image = [[NSImage alloc] initWithContentsOfFile:fileName];
    PDFPage *page = [[PDFPage alloc] initWithImage:image];
    [pdf insertPage:page atIndex: [pdf pageCount]];
    [pdf writeToFile:path];
}

使用上述方法如下:

 NSImage *image = [[NSImage alloc] initWithContentsOfFile:PATH_OF_YOUR_PNG_FILE];
    [self createPdf:image];