PDFKit + SwiftUI

Hello and thanks for reading my post.

I have been trying hard to generate a PDF from a SwiftUI view on a button press.

Looked at the PDFKit documentation, understood that PDFView, PDFDocument and PDFPage are important classes. However, I couldn't find any examples of how to use them in SwiftUI or Swift.

Basically, given a SwiftUI view (or a Swift struct), how to create a new SwiftUI view that displays the generated PDF? The pdf can contain charts, layouts, etc.

Replies

import SwiftUI
import PDFKit

struct PDFViewWrapper: View {
    @State private var pdfDocument: PDFDocument?

    var body: some View {
        VStack {
            if let document = pdfDocument {
                PDFView(document: document)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
            } else {
                Text("PDF not available")
            }
        }
    }
}

struct PDFViewWrapper_Previews: PreviewProvider {
    static var previews: some View {
        PDFViewWrapper()
            .onAppear {
                let generatedPDF = generatePDF() // Replace with your PDF generation code
                PDFDocument(data: generatedPDF) { document in
                    pdfDocument = document
                }
            }
    }
}

func generatePDF() -> Data {
    // Replace with your PDF generation code
    // Return the generated PDF data
    return Data()
}

how about this?