ChallengerGuy
ChallengerGuy

Reputation: 2395

How do I add margins to PDF created by [String] array for printing?

I have an iOS project I'm working using Xcode7 and Swift2. I have an array that is kept in a UITableView. I have an export UIButton that takes the content in the array and separates the strings and puts it in a PDF, line by line, each line being a separated string.

Variables include:

var pdfData = NSMutableData()
bookList: [String] = []

This is part of my code:

    // Loop through book list, increasing each one and displaying individually as string items for body
    for i in 0 ..< bookList.count {
        body += "<p><font size=3><br>\(bookList[i] as String)</br></font></p>"
    }

    html = "\(body)"

    let fmt = UIMarkupTextPrintFormatter(markupText: html)

    // Assign print formatter to UIPrintPageRenderer

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

    // 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")

    // Create PDF context and draw

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

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

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

    UIGraphicsEndPDFContext()

When this PDF file is attached in an email later, it does not have any real margins and if the user wants to print it, it cuts things off. How do I add 1 inch margins for example all the way around each page or pages if it creates one depending on the array length? Thank you.

Upvotes: 1

Views: 798

Answers (1)

ChallengerGuy
ChallengerGuy

Reputation: 2395

I adjusted the page layout to:

 let page = CGRect(x: 50, y: 50, width: 600, height: 750)

This gave it the margins I wanted.

Upvotes: 3

Related Questions