簡體   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