简体   繁体   中英

Code creating black box when converting first page of a pdf for a collection view cell. How to get around this?

I am trying to create a collection view that shows all the pdfs the user has. The cell shows a preview image of the first page of the pdf. I am able to render an image but it is black.

I have tried different ways to show a pdf as a UIImageView but this is the only one that has been able to show something on screen.

func displayContent(document: DocumentModel) {
        let pdf: CGPDFDocument = CGPDFDocument(Bundle.main.url(forResource: document.title, withExtension: ".pdf")! as CFURL)!
        let pdfPage = pdf.page(at: 1)
        let pageRect = pdfPage?.getBoxRect(.mediaBox)
        let renderer = UIGraphicsImageRenderer(size: pageRect!.size)
        let data =  renderer.jpegData(withCompressionQuality: 0.5, actions: { cnv in
            //UIColor.white.set()
            cnv.fill(pageRect!)
            cnv.cgContext.translateBy(x: 0.0, y: pageRect!.size.height)
            cnv.cgContext.scaleBy(x: 1.0, y: -1.0)
            cnv.cgContext.drawPDFPage(pdfPage!)
        })
        self.previewImage.contentMode = .scaleAspectFit
        self.previewImage.clipsToBounds = true
        self.previewImage.image = UIImage(data: data)
        self.documentTitle.text = document.title
}

I should be seeing a lower quality image but I am just seeing a black box instead.

I was able to solve this problem by using this code from hacking with swift

This is the code from the website:

    func drawPDFfromURL(url: URL) -> UIImage? {
        guard let document = CGPDFDocument(url as CFURL) else { return nil }
        guard let page = document.page(at: 1) else { return nil }

        let pageRect = page.getBoxRect(.mediaBox)
        let renderer = UIGraphicsImageRenderer(size: pageRect.size)
        let img = renderer.image { ctx in
            UIColor.white.set()
            ctx.fill(pageRect)

            ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height)
            ctx.cgContext.scaleBy(x: 1.0, y: -1.0)

            ctx.cgContext.drawPDFPage(page)
        }

        return img
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM