繁体   English   中英

如何以编程方式在 iOS 中将 .png 图像转换为 .pdf

[英]How to convert .png image to .pdf in iOS programmatically

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM