我想动态创建一个pdf。但是我有新页面的问题。
目前我正在编写一个文本块,如果该文本块不适合剩余的 Y 位置 - 我将整个文本块写在新页面上。但我想获取整个文本块,尽可能多地写入实际页面,然后将其余部分写在新页面上。有人知道如何根据矩形大小将文本拆分为矩形吗?
这就是代码: writeString ist 来自 CoreData 并且具有动态长度。
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)
}
}