Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a PDF/A file in Swift?

Tags:

ios

pdf

swift

I'd like to create a PDF/A file in my iOS app but don't really know where to start.

My actual code (which generates a simple PDF) is:

_ = UIGraphicsBeginPDFContextToFile(temporaryPdfFilePath, paperSize, nil)
UIGraphicsBeginPDFPageWithInfo(paperSize, nil)
let currentContext: CGContextRef = UIGraphicsGetCurrentContext()!

...drawing...

UIGraphicsEndPDFContext()

Is there any API or something else to follow?

like image 820
Fabrizio Avatar asked Sep 12 '25 18:09

Fabrizio


2 Answers

Prepare html file and then convert to pdf. Swift 3.0 version:

func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -> NSData! {
    let data = NSMutableData()
    UIGraphicsBeginPDFContextToData(data, CGRect.zero, nil)
    UIGraphicsBeginPDFPage()
    printPageRenderer.drawPage(at: 0, in: UIGraphicsGetPDFContextBounds())
    UIGraphicsEndPDFContext()
    return data
}

func exportHTMLContentToPDF(HTMLContent: String) {
    let printPageRenderer = CustomPrintPageRenderer()
    let printFormatter = UIMarkupTextPrintFormatter(markupText: HTMLContent)
    printPageRenderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)
    let pdfData = drawPDFUsingPrintPageRenderer(printPageRenderer: printPageRenderer)
    let pdfFilename = getDocumentsDirectory().appendingPathComponent("nameOfPDFfile.pdf")

    pdfData?.write(to: pdfFilename, atomically: true)
    }
}

Great tutorial: http://www.appcoda.com/pdf-generation-ios/

like image 96
makey Avatar answered Sep 14 '25 10:09

makey


There are quite a few pods to create PDFS easily. I just used SimplePDF and it was a breeze.

SimplePDF: https://github.com/nRewik/SimplePDF

I hope this helps someone.

like image 31
Trevor Avatar answered Sep 14 '25 09:09

Trevor