I am programmatically creating a PDF file from a detail view with a title and body and need to do this for multiple PDF pages if the text is too long for one page.
What I've tried so far is to create an array of the words in the cleanText
and loop through checking the height each time and when big enough for a page, create a new page.
Here is what I have:
- (void) generatePdf: (NSString *)thefilePath :(NSString *) theHeader :(NSString *) theText :(UIImage *) theImage
{
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
int currentPage = 0;
// maximum height and width of the content on the page, byt taking margins into account.
CGFloat maxWidth = kDefaultPageWidth - 2*kBorderInset-2*kMarginInset;
CGFloat maxHeight = kDefaultPageHeight - 2*kBorderInset - 2*kMarginInset;
UIFont *font = [UIFont systemFontOfSize:14.0];
CGFloat currentPageY = 0;
NSString *cleanText;
const char *utfString = [theText UTF8String];
printf ("Converted string = %s\n", utfString);
cleanText = [NSString stringWithUTF8String:utfString];
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
currentPageY = kMarginInset;
// iterate through the words, adding to the pdf each time.
NSArray *words = [cleanText componentsSeparatedByString:@" "];
NSString *word;
for (word in words)
{
// before we render any text to the PDF, we need to measure it, so we'll know where to render the next line.
CGSize size = [word sizeWithFont:font constrainedToSize:CGSizeMake(maxWidth, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
// if the current text would render beyond the bounds of the page,
// start a new page and render it there instead
if (size.height + currentPageY > maxHeight) {
// create a new page and reset the current page's Y value
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
currentPageY = kMarginInset;
}
// render the text
[word drawInRect:CGRectMake(kMarginInset, currentPageY, maxWidth, maxHeight) withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
currentPageY += size.height;
// increment the page number.
}
currentPage++;
// end and save the PDF.
UIGraphicsEndPDFContext();
}