0

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.

Avineet Gupta
  • 586
  • 10
  • 21
  • Not the cleanest way but you can load the PDF file in UIWebView and generate an image from there. – koropok Aug 06 '18 at 10:10
  • How can I do it in background? – Avineet Gupta Aug 06 '18 at 10:11
  • check this out: https://stackoverflow.com/questions/27977758/take-a-full-screenshot-for-all-webview-in-swift – koropok Aug 06 '18 at 10:16
  • I guess its not a optimal solution because I have a list of PDFs in my tableview including other file formats(image / video). – Avineet Gupta Aug 06 '18 at 10:23
  • oh i see. sorry that i couldn't be of any help. – koropok Aug 06 '18 at 10:27
  • Thats Ok at least you give me an idea on which I can work If I couldn't find any other better solution. – Avineet Gupta Aug 06 '18 at 10:30
  • Generating a thumbnail from the PDF on the device (in CoreGraphics world) would not be ideal if you have to download the source PDF to do so (especially in the list view of course). Have you thought about having a script on your server that can generate a preview for your client app to download? – fatuous.logic Aug 06 '18 at 13:35

1 Answers1

2
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
}
crcalin
  • 979
  • 6
  • 13
  • It will return nil at the start. It is only working when file is exists in device not in server. I have already mentioned a link which is having same solution. But Thanks. – Avineet Gupta Aug 08 '18 at 07:16