How to draw text in PDF context in Swift?

后端 未结 2 1997
攒了一身酷
攒了一身酷 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:25

    Sebastian's Answer - Updated for Swift 4.2

    func createPDFFileAndReturnPath() -> String {
    
        let fileName = "pdffilename.pdf"
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0] as NSString
        let pathForPDF = documentsDirectory.appending("/" + fileName)
    
        UIGraphicsBeginPDFContextToFile(pathForPDF, CGRect.zero, nil)
    
        UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: 100, height: 400), nil)
    
        let font = UIFont(name: "System", size: 14.0)
    
        let textRect = CGRect(x: 5, y: 3, width: 125, height: 18)
        let paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
        paragraphStyle.alignment = NSTextAlignment.left
        paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
    
        let textColor = UIColor.black
    
        let textFontAttributes = [
            NSAttributedString.Key.font: font!,
            NSAttributedString.Key.foregroundColor: textColor,
            NSAttributedString.Key.paragraphStyle: paragraphStyle
        ]
    
        let text:NSString = "Hello world"
    
        text.draw(in: textRect, withAttributes: textFontAttributes)
    
        UIGraphicsEndPDFContext()
    
        return pathForPDF
    }
    

提交回复
热议问题