How To Generate PDF in iOS


How To Generate PDF in iOSIn some of the iOS apps there might come a time where developer need to generate there own documents on the fly and be able to export them to the user, it might be for preview, email or to save the document on the device for further use.

Below is the steps for generating PDF in iOS.

 

1. Make a new PDF file and Create a Graphics Context

 

Declare a variable named pageSize of CGSize type to use it to set page size of the document and make a method called “setupPDFDocumentNamed:Width:Height”. Here we will pass the name, width and height of our PDF document in the parameters.

 

 

-(void)setupPDFDocumentNamed:(NSString*)name Width:(float)width  Height:(float)height

{

pageSize = CGSizeMake(width, height);

NSString *newPDFName = [NSString stringWithFormat:@"%@.pdf", name];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,     NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];

UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);

}

 

Inside this method, we are setting the document’s page size and getting the path to our App’s documents directory, and appending our filename to it to get the new PDF’s full path name. In order to create PDF graphics context, we have UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil; in the above method.

 

 

2. Drawing Content

In order to set border add the following lines of code in a new method say drawBorder

 

- (void) drawBorder

{

CGContextRef currentContext = UIGraphicsGetCurrentContext();

UIColor *borderColor = [UIColor blackColor];

CGRect rectFrame = CGRectMake(20, 22, _pageSize.width-20*2, _pageSize.height-20*2);

CGContextSetStrokeColorWithColor(currentContext, borderColor.CGColor);

CGContextSetLineWidth(currentContext, 4);

CGContextStrokeRect(currentContext, rectFrame);

}

 

For adding text to the document add the following lines of code.

 

-(CGRect)addText:(NSString*)text withFrame:(CGRect)frame fontSize:(float)fontSize

{

CGSize stringSize = [text sizeWithFont:font     constrainedToSize:CGSizeMake(_pageSize.width - 2*20-2*20, _pageSize.height - 2*20 -  2*20) lineBreakMode:UILineBreakModeWordWrap];

float textWidth = frame.size.width;

if (textWidth < stringSize.width)

textWidth = stringSize.width;

if (textWidth > _pageSize.width)

textWidth = _pageSize.width – frame.origin.x;

CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth,  stringSize.height);

[text drawInRect:renderingRect

withFont:font

lineBreakMode:UILineBreakModeWordWrap

alignment:UITextAlignmentLeft];

frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);

}

 

For drawing any line (solid fill color box) following lines of code can be added.

 

-(CGRect)addLineWithFrame:(CGRect)frame withColor:(UIColor*)color

{

CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGContextSetStrokeColorWithColor(currentContext, color.CGColor);

CGContextSetLineWidth(currentContext, frame.size.height);

CGPoint startPoint = frame.origin;

CGPoint endPoint = CGPointMake(frame.origin.x + frame.size.width,  frame.origin.y);

CGContextBeginPath(currentContext);

CGContextMoveToPoint(currentContext, startPoint.x, startPoint.y);

CGContextAddLineToPoint(currentContext, endPoint.x, endPoint.y);

CGContextClosePath(currentContext);

CGContextDrawPath(currentContext, kCGPathFillStroke);

return frame;

}

 

To add an image following lines of code can be used which will draw the image in the rect specified and will return the image frame in which image was set.

 

-(CGRect)addImage:(UIImage *)image atPoint:(CGPoint)point

{

CGRect imageFrame = CGRectMake(point.x, point.y, 80, 80);

[image drawInRect:imageFrame];

return imageFrame;

}

 

 

3. Generate PDF

Make an IBAction Method to generate PDF on click of a button. Add the following lines of code, which will pass the data of text, lines and image in the methods used to generate these graphics.

 

-(IBAction)generatePDFOnBtnClcik:(id)sender

{

[self setupPDFDocumentNamed:@"SAMPLE PDF" Width:255 Height:166];

UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, _pageSize.width,     _pageSize.height), nil);

[self addText:@"GENERATING SAMPLE PDF"

withFrame:CGRectMake(20, 2, 255, 34) fontSize:15.0f];

[self addText:@"APRIL - 2014"

withFrame:CGRectMake(68, 20, 255, 17) fontSize:15.0f];

[self addLineWithFrame:CGRectMake(3, 38, _pageSize.width - 3*2, 1) withColor:[UIColor darkGrayColor]];

[self addLineWithFrame:CGRectMake(3, 128, _pageSize.width - 3*2, 1) withColor:[UIColor darkGrayColor]];

[self addText:@"Adding text of different size"

withFrame:CGRectMake(20, 45, 109, 13) fontSize:11.0f];

[self addText:@"Adding another text" withFrame:CGRectMake(20, 60, 180, 11) fontSize:11.0f];

[self addText:@"Small Text" withFrame:CGRectMake(3, 130, 150, 12) fontSize:10.0f];

NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", IMAGE_PATH, ImageString]]];

ImageView.image = [UIImage imageWithData:imageData]; //to add image in the PDF

[self addImage:ImageView.image

atPoint:CGPointMake(160, 42)];

UIGraphicsEndPDFContext();//to finish PDF

 }

 

Image  Source: wikimedia.org