UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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!

2      

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.

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.