How can I programmatically generate a thumbnail of a PDF with iOS?

后端 未结 4 887
执笔经年
执笔经年 2020-12-28 09:24

We\'re displaying PDF content using UIWebViews at the moment. Ideally I would like to be able to display thumbnails in the UITableView without loa

4条回答
  •  一整个雨季
    2020-12-28 09:46

    Here is a swift 3 method for generating a UIImage thumbnail for a pdf page

    static func getThumbnailForPDF(_ urlString:String, pageNumber:Int) -> UIImage? {
        let bundle = Bundle.main
        let path = bundle.path(forResource: urlString, ofType: "pdf")
        let pdfURL = URL(fileURLWithPath: path!)
    
        let pdf = CGPDFDocument(pdfURL as CFURL )!
        let page = pdf.page(at: pageNumber)!
        let rect = CGRect(x: 0, y: 0, width: 100.0, height: 70.0) //Image size here
    
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()!
    
        context.saveGState()
        context.translateBy(x: 0, y: rect.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.setFillColor(gray: 1.0, alpha: 1.0)
        context.fill(rect)
    
    
        let pdfTransform = page.getDrawingTransform(CGPDFBox.mediaBox, rect: rect, rotate: 0, preserveAspectRatio: true)
        context.concatenate(pdfTransform)
        context.drawPDFPage(page)
    
        let thumbImage = UIGraphicsGetImageFromCurrentImageContext()
        context.restoreGState()
    
        UIGraphicsEndImageContext()
    
        return thumbImage
    }
    

提交回复
热议问题