Reputation: 596
I want show thumbnail of a PDF file stored in a server in my UIImageView.
I have target my app for iOS 9 so PDFKit doesn't work for me.
I have also gone through various solutions but none of worked for me. Example - https://stackoverflow.com/a/4768524/4152591
Can anyone here who have gone through similar problem?
Thanks in advance.
Upvotes: 0
Views: 1632
Reputation: 1049
private func thumbnailFromPdf(withUrl url: URL, pageNumber: Int = 1, width: CGFloat = 240) enter code here-> UIImage? {
guard
let pdf = CGPDFDocument(url as CFURL),
let page = pdf.page(at: pageNumber)
else { return nil }
var pageRect = page.getBoxRect(.mediaBox)
let pdfScale = width / pageRect.size.width
pageRect.size = CGSize(width: pageRect.size.width * pdfScale, height: pageRect.size.height * pdfScale)
pageRect.origin = .zero
UIGraphicsBeginImageContext(pageRect.size)
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(UIColor.white.cgColor)
context.fill(pageRect)
context.saveGState()
context.translateBy(x: 0.0, y: pageRect.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.concatenate(page.getDrawingTransform(.mediaBox, rect: pageRect, rotate: 0, preserveAspectRatio: true))
context.drawPDFPage(page)
context.restoreGState()
}
let image = UIGraphicsGetImageFromCurrentImageContext()
defer { UIGraphicsEndImageContext() }
return image
}
Upvotes: 2