【问题标题】:How to convert .png image to .pdf in iOS programmatically如何以编程方式在 iOS 中将 .png 图像转换为 .pdf
【发布时间】:2011-06-16 12:48:47
【问题描述】:

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

【问题讨论】:

标签: ios objective-c image pdf


【解决方案1】:

使用以下代码从图像创建 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();

【讨论】:

    【解决方案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];
    

    【讨论】:

    • 这里的PDFDocument和PDFPage是什么? OP 询问了有关 iPhone 开发的问题。
    猜你喜欢
    • 2011-07-07
    • 2011-10-12
    • 2013-02-09
    • 1970-01-01
    • 2017-03-12
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多