Madan Mohan
Madan Mohan

Reputation: 8820

How to convert .png image to .pdf in iOS programmatically

How to convert image of format .png to .pdf file?

Upvotes: 3

Views: 10217

Answers (2)

Ganesh Amrule
Ganesh Amrule

Reputation: 427

Use following code to create PDF file from image.

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();

Upvotes: 0

Prike
Prike

Reputation: 65

-(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];
}

USE the above method as follow :

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

Upvotes: -3

Related Questions