DEV Community

Utku Y.
Utku Y.

Posted on

Turning SwiftUI Views into PDFs: A Quick How-To

Need to generate a PDF from a SwiftUI view? Whether it's for sharing a report, creating a simple document, or any other purpose, SwiftUI's ImageRenderer offers a straightforward way to achieve this.

Here's a handy function that takes a SwiftUI view (ViewForPDFOutput in this example) and returns the URL of the generated PDF file:

struct Example: View { var body: some View { VStack { Text("demo") } .toolbar { buildShareButton() } } private func buildShareButton() -> some ToolbarContent { ToolbarItem(placement: .topBarTrailing) { ShareLink(item: getPdfUrl()) { Image(systemName: "square.and.arrow.up") } } } private func getPdfUrl() -> URL { let renderer = ImageRenderer( content: ViewForPDFOutput().frame(width: 500) ) let url = URL.documentsDirectory.appending(path: "swiftui_output.pdf") renderer.render { size, context in var box = CGRect(x: 0, y: 0, width: size.width, height: size.height) guard let pdf = CGContext(url as CFURL, mediaBox: &box, nil) else { return } pdf.beginPDFPage(nil) context(pdf) pdf.endPDFPage() pdf.closePDF() } return url } } 
Enter fullscreen mode Exit fullscreen mode

Note: It's important to give width to view which you want to make pdf.

.frame(width: 500) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)