I would like to create a pdf dynamically. But I have problems with new pages.
Currently I am writing a text block and if that text block does not fit to the remaining Y position - I write the whole text block on a new page. But I would like to take the whole text block, write to the actual page as much as I can and write the rest on a new page. Does someone know how to split the text in a rect depending on the rect size?
Thats the code: writeString ist coming from CoreData and has a dynamic length.
func drawTextBlock(pdfFileName: String, writeString: NSString = " ", fontSize: CGFloat = 12.0, fontName: String = "Helvetica", textAlignment: NSTextAlignment = NSTextAlignment.Natural) {
//Text attribute configuration
let font = UIFont(name: fontName, size: fontSize)
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = textAlignment
let textFontAttributes = [
NSFontAttributeName: font!,
NSParagraphStyleAttributeName: textStyle
]
let textSize = writeString.sizeWithAttributes(textFontAttributes)
let linesNeeded = ceil(textSize.width / (myPageCalibration.pageWidth - myPageCalibration.xOffsetLeft - myPageCalibration.xOffsetRight))
if remainingSpaceY >= (textSize.height * linesNeeded) {
//draw text in rectangle
writeString.drawInRect(CGRectMake(myPageCalibration.xOffsetLeft, myPageCalibration.yOffsetUp + currentPositionY, myPageCalibration.pageWidth - myPageCalibration.xOffsetLeft - myPageCalibration.xOffsetRight, (textSize.height * linesNeeded )), withAttributes: textFontAttributes)
//calc remainingSpace
currentPositionY = CGFloat(linesNeeded * textSize.height) + currentPositionY
remainingSpaceY = remainingSpaceY - (textSize.height * linesNeeded)
}
else {
//next page
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 595, 842), nil);
remainingSpaceY = myPageCalibration.pageHeight - myPageCalibration.yOffsetDown - myPageCalibration.yOffsetUp
currentPositionY = 0
drawTextBlock(pdfFileName, writeString: writeString, fontSize: fontSize, fontName: fontName, textAlignment: textAlignment)
}
}