How to draw text in PDF context in Swift?

I have a simple function that creates a PDF file and returns its path.

func createPDFFileAndReturnPath() -> String { let fileName = "pdffilename.pdf" let paths = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true) let documentsDirectory = paths[0] let pathForPDF = documentsDirectory.stringByAppendingString("/" + fileName) UIGraphicsBeginPDFContextToFile(pathForPDF, CGRectZero, nil) UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 100, 400), nil) let text = "text" //how to print this in whatever place? //text.drawInRect - this doesn't work UIGraphicsEndPDFContext() return pathForPDF } 
+3
source share
1 answer

Here is your function:

 func createPDFFileAndReturnPath() -> String { let fileName = "pdffilename.pdf" let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let documentsDirectory = paths[0] as! NSString let pathForPDF = documentsDirectory.stringByAppendingString("/" + fileName) UIGraphicsBeginPDFContextToFile(pathForPDF, CGRectZero, nil) UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 100, 400), nil) let font = UIFont(name: "Helvetica Bold", size: 14.0) let textRect = CGRectMake(5, 3, 125, 18) var paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paragraphStyle.alignment = NSTextAlignment.Left paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping let textColor = UIColor.blackColor() let textFontAttributes = [ NSFontAttributeName: font!, NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName: paragraphStyle ] let text:NSString = "Hello world" text.drawInRect(textRect, withAttributes: textFontAttributes) UIGraphicsEndPDFContext() return pathForPDF } 
+8
source

All Articles