Building a Custom PDF Generator in SwiftUI (Export & Share PDFs)
Generating PDFs is a common requirement in modern iOS apps, whether it’s for invoices, reports, or certificates. SwiftUI, combined with UIKit
capabilities, makes it easy to create, export, and share PDFs seamlessly.
In this guide, we’ll cover:
✅ Generating a PDF from SwiftUI views
✅ Exporting and saving the PDF file
✅ Sharing the generated PDF using the Share Sheet
✅ Adding custom styling & layouts to the PDF
🔹 Step 1: Creating a PDF from SwiftUI View
SwiftUI doesn’t have a built-in PDF generator, so we’ll use UIGraphicsPDFRenderer
from UIKit. We’ll first create a function that converts a SwiftUI view into a UIImage
and then render it as a PDF.
Helper Function: Convert SwiftUI View to UIImage
import SwiftUI
extension View {
func snapshot() -> UIImage {
let controller = UIHostingController(rootView: self)
let view = controller.view
let targetSize = view?.intrinsicContentSize ?? CGSize(width: 300, height: 400)
view?.bounds = CGRect(origin: .zero, size: targetSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { _ in
view?.drawHierarchy(in: view!.bounds, afterScreenUpdates: true)
}
}
}
This function captures any SwiftUI view as an image, which we can then use for generating PDFs.
🔹 Step 2: Generating the PDF File
We will now create a function to render the captured image as a PDF.
import UIKit
func generatePDF(from image: UIImage) -> URL? {
let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, size: image.size))
let url = FileManager.default.temporaryDirectory.appendingPathComponent("GeneratedPDF.pdf")
do {
try pdfRenderer.writePDF(to: url, withActions: { context in
context.beginPage()
image.draw(in: CGRect(origin: .zero, size: image.size))
})
return url
} catch {
print("Error generating PDF: \(error.localizedDescription)")
return nil
}
}
This function:
- Takes a
UIImage
and converts it into a PDF. - Saves the PDF in the temporary directory.
🔹 Step 3: Sharing the PDF
Once we generate the PDF, we can allow users to share it using SwiftUI’s ShareSheet
.
import UIKit
import SwiftUI
struct ShareSheet: UIViewControllerRepresentable {
let activityItems: [Any]
func makeUIViewController(context: Context) -> UIActivityViewController {
return UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}
Using the ShareSheet in SwiftUI
struct ContentView: View {
@State private var showShareSheet = false
@State private var pdfURL: URL?
var body: some View {
VStack {
Text("Hello, SwiftUI PDF!")
.font(.title)
.padding()
.background(Color.yellow.cornerRadius(10))
.padding()
Button("Generate & Share PDF") {
let image = Text("SwiftUI PDF Example").snapshot()
pdfURL = generatePDF(from: image)
showShareSheet = true
}
.padding()
.background(Color.blue.cornerRadius(10))
.foregroundColor(.white)
}
.sheet(isPresented: $showShareSheet) {
if let pdfURL = pdfURL {
ShareSheet(activityItems: [pdfURL])
}
}
}
}
This will generate a PDF of the SwiftUI text and allow the user to share it.
🎯 Final Thoughts
✅ SwiftUI can easily generate and share PDFs using UIViewControllerRepresentable
.
✅ You can capture SwiftUI views as images and render them into a PDF format.
✅ Enhance your app with features like multi-page PDFs, text formatting, and images.
Now you can generate, export, and share PDFs effortlessly in SwiftUI! 🚀
Comments
Post a Comment