For reading pdf files, I got some very good coding ideas from another thread. My routine works fine for displaying a fixed file name, e.g. MyFile.pdf.
But I want to implement a general PDF reader, and I’m having a difficult time passing a variable file name into the PDFUIView structure.
How can I pass a different file name to the reader?
How can I set the reader to start with a pdf page number (variable) other than 0?
This is the Nav link I use to call the reader from the Main view. It’s within a NavigationView, so works ok.
NavigationLink {
PDFUIView()
} label: {
Image(systemName: "doc.richtext")
}
This is the reader I set up using the coding based on the other thread.
import SwiftUI
import PDFKit
struct PDFUIView: View {
let pdfDoc: PDFDocument
var pdfName = "MyFile"
init() {
let url = Bundle.main.url(forResource: pdfName, withExtension: "pdf")!
pdfDoc = PDFDocument(url: url)!
}
var body: some View {
PDFKitView(showing: pdfDoc)
}
}
struct PDFKitView: UIViewRepresentable {
let pdfDocument: PDFDocument
init(showing pdfDoc: PDFDocument) {
self.pdfDocument = pdfDoc
}
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
}
}