BLACK FRIDAY SALE: Save 50% 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.

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.