How can I open a local PDF file using a SwiftUI button?
I want to display a local PDF file through a new view when I tap a button. I tried doing that using a UIViewRepresentable WebView but it's not working (I have worked with WebView only through NavigationList).
I leave my code, but feel free to suggest better option if the WebView is not the most optimal.
ButtonView
import SwiftUI
struct ResumeView: View {
let sfSymbol: String
let text: String
let fileUrl = Bundle.main.path(forResource: "Resume", ofType: "pdf")
var body: some View {
RoundedRectangle(cornerRadius: 25)
.fill(Color.white)
.frame(height: 50.0)
.overlay(
HStack {
Image(systemName: sfSymbol)
.foregroundColor(.init(red: 0.20, green: 0.33, blue: 0.55, opacity: 1.00))
Button(action: {
WebView(urlString: self.fileUrl)
}) {
Text(text)
.foregroundColor(.black)
}
})
}
}
WebView
import Foundation
import SwiftUI
import WebKit
struct WebView: UIViewRepresentable {
let urlString: String?
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<WebView>) {
if let safeUrlString = urlString {
if let url = URL(string: safeUrlString) {
let request = URLRequest(url: url)
uiView.load(request)
}
}
}
}
Solution 1:
Using PDFKit
we load local PDF
file. Please try below code.
import SwiftUI
struct ResumeView: View {
....
let fileUrl = Bundle.main.url(forResource: "Resume", withExtension: "pdf")!
var body: some View {
....
Button(action: {
PDFKitView(url: self.fileUrl)
}) {
Text(text)
.foregroundColor(.black)
}
....
}
}
PDFKitView
import PDFKit
struct PDFKitView: View {
var url: URL
var body: some View {
PDFKitRepresentedView(url)
}
}
struct PDFKitRepresentedView: UIViewRepresentable {
let url: URL
init(_ url: URL) {
self.url = url
}
func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
let pdfView = PDFView()
pdfView.document = PDFDocument(url: self.url)
pdfView.autoScales = true
return pdfView
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
// Update the view.
}
}