Skip to content

Instantly share code, notes, and snippets.

@oalansari82
Created May 15, 2018 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oalansari82/d6ad3554cf72754798319ea1e8066142 to your computer and use it in GitHub Desktop.
Save oalansari82/d6ad3554cf72754798319ea1e8066142 to your computer and use it in GitHub Desktop.
class PdfTools {
func generatePdfFromCollectionView(_ collectionView: UICollectionView?, filename:String, success:(String) -> ()) {
guard let collectionView = collectionView else {
return
}
let pdfData = NSMutableData()
let contentArea = CGRect(
x: 0,
y: 0,
width: collectionView.frame.width,
height: collectionView.frame.height
)
collectionView.frame = contentArea
UIGraphicsBeginPDFContextToData(pdfData, contentArea, nil)
UIGraphicsBeginPDFPage()
collectionView.drawHierarchy(in: collectionView.bounds, afterScreenUpdates: true)
UIGraphicsEndPDFContext()
if let filepath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
let fileFullPath = filepath + "/" + filename
if pdfData.write(toFile: fileFullPath, atomically: true) {
success(fileFullPath)
}
}
}
}
let pdf = PdfTools()
pdf.generatePdfFromCollectionView(self.collectionView, filename: "myorder.pdf") { (filename) in
print(filename) // prints file location
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment