You create a PDF graphics context using either the UIGraphicsBeginPDFContextToData or the UIGraphicsBeginPDFContextToFile function. These functions create the graphics context and associate it with a destination for the PDF data. For the UIGraphicsBeginPDFContextData function, the destination is an NSMutableData object that you provide. And for the UIGraphocsBeginPDFContextToFile function, the destination is a file in your app's Home directory
PDF documents organize their content in a page-based structure. This structure imposes two restrictions on any drawing you do.
- There must be an open page before you issue any drawing commands.
- You must specify the size of each page.
GraphicsBeginPDFPage or UIGraphicsBeginPDFPageWithInfo functions
Each time you want to create a new page, you must call one of these functions again to mark the start of the new page. The UIGraphicsBeginPDFPage function creates a page using the default size, while the UIGraphicsBeginPDFPageWithInfo function lets you customize the page size and other page attributes.
- let pdfData = NSMutableData()
- let imgView = UIImageView.init(image: image)
- let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
- UIGraphicsBeginPDFContextToData(pdfData, imageRect, nil)
- UIGraphicsBeginPDFPage()
- let context = UIGraphicsGetCurrentContext()
- imgView.layer.render(in: context!)
- UIGraphicsEndPDFContext()
-
- let fileManager = FileManager.default
- let dir = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("PDFDocument")
- if !fileManager.fileExists(atPath: dir) {
- try! fileManager.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil)
- }
- let url = NSURL(string: dir)
- let path = url!.appendingPathComponent("\(filename).pdf")?.absoluteString
- do {
- try pdfData.write(toFile: path!, options: NSData.WritingOptions.atomic)
- } catch let error as NSError{
- print(error.localizedDescription)
- }