Created
January 21, 2017 02:32
-
-
Save amelnikov78/582f35a289dc5a105aa19cf7e96e80dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIImage { | |
static func fromPDF(filename: String, size: CGSize) -> UIImage? { | |
guard let path = Bundle.main.path(forResource: filename, ofType: "pdf") else { return nil } | |
let url = URL(fileURLWithPath: path) | |
guard let document = CGPDFDocument(url as CFURL) else { return nil } | |
guard let page = document.page(at: 1) else { return nil } | |
let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height) | |
if #available(iOS 10.0, *) { | |
let renderer = UIGraphicsImageRenderer(size: size) | |
let img = renderer.image { ctx in | |
UIColor.white.withAlphaComponent(0).set() | |
ctx.fill(imageRect) | |
ctx.cgContext.translateBy(x: 0, y: size.height) | |
ctx.cgContext.scaleBy(x: 1.0, y: -1.0) | |
ctx.cgContext.concatenate(page.getDrawingTransform(.artBox, rect: imageRect, rotate: 0, preserveAspectRatio: true)) | |
ctx.cgContext.drawPDFPage(page); | |
} | |
return img | |
} else { | |
// Fallback on earlier versions | |
UIGraphicsBeginImageContextWithOptions(size, false, 2.0) | |
if let context = UIGraphicsGetCurrentContext() { | |
context.interpolationQuality = .high | |
context.setAllowsAntialiasing(true) | |
context.setShouldAntialias(true) | |
context.setFillColor(red: 1, green: 1, blue: 1, alpha: 0) | |
context.fill(imageRect) | |
context.saveGState() | |
context.translateBy(x: 0.0, y: size.height) | |
context.scaleBy(x: 1.0, y: -1.0) | |
context.concatenate(page.getDrawingTransform(.cropBox, rect: imageRect, rotate: 0, preserveAspectRatio: true)) | |
context.drawPDFPage(page) | |
let image = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return image | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment