1

Looking for a solution to create a pdf programatically with the contents of my UITabelView with a label on top and allow the users to print on standard A4 paper.

This is my not working code:

        func createPdfFromView(aView: UIView, saveToDocumentsWithFileName fileName: String) {
     let pdfTitle = "\(pilotName)'s Past Duty"
    let pageSize = CGRect(x: 0, y: 0, width: 11 * 70, height: 8.5 * 70)
    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, pageSize, nil)
    UIGraphicsBeginPDFPage()
        let font = UIFont.preferredFont(forTextStyle: .largeTitle)
        let attributedPDFTitle = NSAttributedString(string: pdfTitle, attributes: [NSAttributedString.Key.font: font])
        let stringSize = attributedPDFTitle.size()
        let stringRect = CGRect(x: (pageSize.width / 2 - stringSize.width / 2), y: 20, width: stringSize.width, height: stringSize.height)
        attributedPDFTitle.draw(in: stringRect)
    aView.layer.render(in: UIGraphicsGetCurrentContext()!)
        UIGraphicsGetCurrentContext()!.translateBy(x: 0, y: 40)
    UIGraphicsEndPDFContext()

    if let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
        let documentsFileName = documentDirectories + "/" + fileName
        debugPrint(documentsFileName)
        pdfData.write(toFile: documentsFileName, atomically: true)
    }
}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.