Sanjay Singh
Sanjay Singh

Reputation: 11

How to create PDF in Swift

I want to create a PDF using UIWebView. As I have any work sheet details and I want to save generate PDF in Swift. I'm using HTML format with tables but in second page my border is cutting.

Upvotes: 1

Views: 3359

Answers (1)

ares777
ares777

Reputation: 3628

For Swift 2 I used to use html string (is the exact html code used for your table) as String! Then

    let render = UIPrintPageRenderer()
    let fmt = UIMarkupTextPrintFormatter(markupText: html)

    render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)

    // 3. Assign paperRect and printableRect

    let page = CGRect(x: 0, y: 0, width: 612, height: 792) // some defaults
    let printable = page.insetBy(dx: 0, dy: 0)

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

    // 4. Create PDF context and draw
    //let pointzero = CGPoint(x: 0,y :0)
    let rect = CGRect.zero
    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)

    for i in 0..<render.numberOfPages {
        UIGraphicsBeginPDFPage();
        render.drawPageAtIndex( i, inRect: UIGraphicsGetPDFContextBounds())
    }

    UIGraphicsEndPDFContext();

    // 5. Save PDF file
   let path = "\(NSTemporaryDirectory())sd.pdf"

    pdfData.writeToFile( path, atomically: true)
    print("open \(path)")

Upvotes: 3

Related Questions