How to draw text in PDF context in Swift?

后端 未结 2 2002
攒了一身酷
攒了一身酷 2020-12-05 21:16

I have a simple function that create pdf file and return its path.

func createPDFFileAndReturnPath() -> String {

    let fileName = \"pdffilename.pdf\"
          


        
2条回答
  •  醉话见心
    2020-12-05 21:46

    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
    }
    

提交回复
热议问题