swiftios-pdfkitapple-pdfkit

Swift PDF render any UIView or UIViewController PDFKit


I made some research, I found that I can draw Image, Strings, Shapes with the PDFKit library. Is there any easy way to draw a UIView or the view of a UIViewController inside the PDF document?

I prefer a Swift answer, but I will accept Objective-C too.


Solution

  • The UIView as well as the view contained into the UIViewController, can be rendered with the layer:

    Get the context:

    let context = UIGraphicsGetCurrentContext()!
    

    UIView :

    view.layoutIfNeeded()
    view.layer.render(in: context)
    

    UIViewController

    controller.loadViewIfNeeded()
    controller.view.layer.render(in: context)
    

    Full working script:

    let pdfMetadata =
    [
        kCGPDFContextCreator: "MyAppName",
        kCGPDFContextAuthor: "TheAuthor"
    ]
    UIGraphicsBeginPDFContextToFile(filePath, CGRect.zero, pdfMetadata)
    
    let context = UIGraphicsGetCurrentContext()!
    
    UIGraphicsBeginPDFPage()
    
    controller.loadViewIfNeeded()
    controller.view.layer.render(in: context)
    
    UIGraphicsEndPDFContext()