godmoney godmoney - 3 months ago 23
iOS Question

Create dynamic pdf documents on iOS

How can I create dynamic pdf documents on iOS?
I can be done using either objective-c/swift but should support dynamic content and different number of pages for each document.
Every PDF document creation should be done "on the fly" without the use of templates.


To draw some text in our PDF, we’re going to need to use the Core Text framework. To do this, select the project target and go to the Build Phases tab. Click the + sign below the Link Binaries With Libraries option, and then select the CoreText framework.

Then open ViewController.h and import the CoreText header:

#import <CoreText/CoreText.h>

Add a new method to ViewController.m to create a “hello world” PDF.

NSString* fileName = @"Invoice.PDF";

NSArray *arrayPaths =
NSString *path = [arrayPaths objectAtIndex:0];
NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];

NSString* textToDraw = @"Hello World";
CFStringRef stringRef = (__bridge CFStringRef)textToDraw;

// Prepare the text using a Core Text Framesetter.
CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, stringRef, NULL);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);

CGRect frameRect = CGRectMake(0, 0, 300, 50);
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);

// Get the frame that will do the rendering.
CFRange currentRange = CFRangeMake(0, 0);
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);

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

// Get the graphics context.
CGContextRef currentContext = UIGraphicsGetCurrentContext();

// Put the text matrix into a known state. This ensures
// that no old scaling factors are left in place.
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);

// Core Text draws from the bottom-left corner up, so flip
// the current transform prior to drawing.
CGContextTranslateCTM(currentContext, 0, 100);
CGContextScaleCTM(currentContext, 1.0, -1.0);

// Draw the frame.
CTFrameDraw(frameRef, currentContext);


// Close the PDF context and write the contents out.



1. How to create a pdf with quartz-2d in ios part-1

2. How to create a pdf with quartz 2d in ios part-2

For More on CoreText framework

1. Core text tutorial for ios making a magazine app

2. About Core Text - Apple Doc

3. SO Doc - PDF Creation in iOS