BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

How can I view a PDF file in my ScrollView?

Forums > SwiftUI

Hi there,

I have a relatively simple questions, as the title suggests...

I have a PDF file in my appbundle that I would like to present to the user in a scroll view to read. Is it possible to open a pdf natively in SwiftUI?

Most of the research I have read online says this isnt the case, and this work will need to be completed with UIKit (:0).

Thank you all and hope you are enjoying the summer!

   

No, there is no "native" SwiftUI View to display a PDF. You need to have a UIViewRepresentable that wraps a PDFView. Something like this very simple example:

import SwiftUI
import PDFKit

struct PDFKitView: UIViewRepresentable {

    let pdfDocument: PDFDocument

    init(showing pdfDoc: PDFDocument) {
        self.pdfDocument = pdfDoc
    }

    //you could also have inits that take a URL or Data

    func makeUIView(context: Context) -> PDFView {
        let pdfView = PDFView()
        pdfView.document = pdfDocument
        pdfView.autoScales = true
        return pdfView
    }

    func updateUIView(_ pdfView: PDFView, context: Context) {
        pdfView.document = pdfDocument
    }
}

struct PDFUIView: View {

    let pdfDoc: PDFDocument

    init() {
        //for the sake of example, we're going to assume 
        //you have a file Lipsum.pdf in your bundle
        let url = Bundle.main.url(forResource: "Lipsum", withExtension: "pdf")!
        pdfDoc = PDFDocument(url: url)!
    }

    var body: some View {
        PDFKitView(showing: pdfDoc)
    }
}

I'll leave it to you to adapt this for use with a ScrollView.

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.