Reputation: 95
In xcode
, how would I convert a UIImage
into a PDF
File? Once I figure this out, I will send it through an email. But everything I've found while researching, it results as a blank file or gives an error saying it's damaged. How should I convert it?
Upvotes: 0
Views: 2826
Reputation: 1
First you need to create a PDF graphics context that is GraphicsBegin and GraphicsEndPDFContext. Your image from current view will capture and it will set on your PDF page.
Steps:
First call this method on any of your button tap event:
NSString *fileName = [NSString stringWithFormat:@“pdf file name here”];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
// This method will generate pdf file of your image. You can send that pdf file after this method.
[self generatePdfWithFilePath: pdfFileName];
Then set these methods in your view controller:
- (void) generatePdfWithFilePath: (NSString *)thefilePath
{
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 500, 810), nil);
[self drawImage:@“page number of pdf file”];
UIGraphicsEndPDFContext();
}
- (void) drawImage:(NSInteger)pageNumber
{
UIImage * demoImage1;
demoImage1 = [self captureView:@“Your image view”];
[demoImage1 drawInRect:CGRectMake(0, 0, 500, 810)];
}
- (UIImage *)captureView:(UIView *)view {
CGRect screenRect = view.frame;
UIGraphicsBeginImageContext(screenRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, screenRect);
[view.layer renderInContext:ctx];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Upvotes: 0
Reputation: 1060
1. Download Source File From Step 4
2. Import into your Project
3. Put This code into your action
NSData *pdfData = [[NSData alloc] init];
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
pdfData = [PDFImageConverter convertImageToPDF:chosenImage];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents/image.pdf"];
[pdfData writeToFile:path atomically:NO];
4. Enjoy PDFImageConverter
Upvotes: 0
Reputation: 798
-(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];
PDFDocument Class conforms to NSObject. You can use this PDFDocument class in the PDFKit Framework.
Upvotes: 2