ChallengerGuy ChallengerGuy - 1 year ago 550
iOS Question

Create and store PDF document programmatically using Swift for iOS

I have an app that can view a PDF that is already stored within the project. I want to be able to create a new PDF document and store it in the app directory to later view in the already existing viewer. The PDF would be created from an array

var todoList: [String] = []
that is displayed on a
. I know to create a PDF, I have to create a file name, path, and directory. I don't know how to do this. I saw online reference to URL and URL request, but I'm not sure if this is the correct avenue for what I want to do. Can someone please give me some advice and guidance? Everything I can find is for Objective-C.

Answer Source

I used this code to create and save the file (using HTLM)

func createPDF() {
    let html = "<b>Hello <i>World!</i></b> <p>Generate PDF file from HTML in Swift</p>"
    let fmt = UIMarkupTextPrintFormatter(markupText: html)

    // 2. Assign print formatter to UIPrintPageRenderer

    let render = UIPrintPageRenderer()
    render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)

    // 3. Assign paperRect and printableRect

    let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
    let printable = CGRectInset(page, 0, 0)

    render.setValue(NSValue(CGRect: page), forKey: "paperRect")
    render.setValue(NSValue(CGRect: printable), forKey: "printableRect")

    // 4. Create PDF context and draw

    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil)

    for i in 1...render.numberOfPages() {

        let bounds = UIGraphicsGetPDFContextBounds()
        render.drawPageAtIndex(i - 1, inRect: bounds)


    // 5. Save PDF file

    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

    pdfData.writeToFile("\(documentsPath)/file.pdf", atomically: true)

Then i loaded it into UIWebView from documents directory with this code

func loadPDF(filename: String) {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let filePath = "\(documentsPath)/\(filename).pdf"
    let url = NSURL(fileURLWithPath: filePath)
    let urlRequest = NSURLRequest(URL: url)