Is it possible to display PDF thumbnails in SwiftUI app?

I am interested in knowing if it is possible to show thumnail images of pdf files in a SwiftUI app like it is with UIKit? And if so, how?

I want to be able to fetch PDF files from Firebase Storage and then display these PDFs in the app.

I haven't been able to find anything describing this use case...

Upvotes: 3

Views: 2652

Answers (1)

jnpdx
jnpdx

Reputation: 52535

To display a PDF thumbnail in SwiftUI, you'll need to wrap PDFThumbnailView, which is a UIView in UIViewRepresentable.

Something like:

import PDFKit
import SwiftUI

struct PDFThumbnailRepresented : UIViewRepresentable {
    var pdfView : PDFView
    
    func makeUIView(context: Context) -> PDFThumbnailView {
        let thumbnail = PDFThumbnailView()
        thumbnail.pdfView = pdfView
        thumbnail.thumbnailSize = CGSize(width: 100, height: 100)
        thumbnail.layoutMode = .horizontal
        return thumbnail
    }
    
    func updateUIView(_ uiView: PDFThumbnailView, context: Context) {
        //do any updates you need
        //you could update the thumbnailSize to the size of the view here if you want, for example
        //uiView.thumbnailSize = uiView.bounds.size
    }
}

You'd use it by passing a PDFView: PDFThumbnailRepresented(pdfView: pdfView)

To create your PDFView, you'll need to get the data or url and create it something like:

guard let path = Bundle.main.url(forResource: "example", withExtension: "pdf") else { return }

if let document = PDFDocument(url: path) {
    pdfView.document = document
}

Note the above sample is if it was in your app's Bundle. Your question about loading it from Firebase Storage is beyond the scope of just this question which I'm assuming to be about just displaying the PDF thumbnail in SwiftUI.

More resources about loading/creating the PDFThumbnailView, not including wrapping it like I did above: https://www.hackingwithswift.com/example-code/libraries/how-to-show-pdf-thumbnails-using-pdfthumbnailview

Upvotes: 5

Related Questions