iOS development
UIView
PDF conversion
Swift programming
mobile app development

How to Convert UIView to PDF within iOS?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Exporting a UIView to PDF is common for receipts, reports, forms, and shareable app documents. The core workflow is straightforward: render the view into a PDF context, save data to file, then share or store it. Production quality depends on layout timing, pagination, and file lifecycle management.

Render a View to PDF Data

Use UIGraphicsPDFRenderer for modern iOS PDF generation.

swift
1import UIKit
2
3func pdfData(from view: UIView) -> Data {
4    let bounds = view.bounds
5    let renderer = UIGraphicsPDFRenderer(bounds: bounds)
6
7    return renderer.pdfData { context in
8        context.beginPage()
9        view.layer.render(in: context.cgContext)
10    }
11}

This produces a single-page PDF with the current view appearance.

Ensure View Layout Is Final Before Rendering

If layout has not completed, the PDF can be blank or clipped. Force layout before calling renderer.

swift
1func prepareForExport(_ view: UIView) {
2    view.setNeedsLayout()
3    view.layoutIfNeeded()
4}

Call this on main thread, because UIKit rendering is not thread-safe.

Save PDF to App Storage

After generating PDF data, write it to a file path in app storage.

swift
1import Foundation
2
3func savePDF(_ data: Data, fileName: String) throws -> URL {
4    let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
5    let url = docs.appendingPathComponent(fileName)
6    try data.write(to: url, options: .atomic)
7    return url
8}

Putting both together:

swift
1prepareForExport(myView)
2let data = pdfData(from: myView)
3let url = try savePDF(data, fileName: "report.pdf")
4print(url)

Share Generated PDF

Use UIActivityViewController to share through Files, Mail, AirDrop, or messages.

swift
1import UIKit
2
3func sharePDF(_ url: URL, from controller: UIViewController) {
4    let activity = UIActivityViewController(activityItems: [url], applicationActivities: nil)
5    controller.present(activity, animated: true)
6}

On iPad, configure popover source to avoid presentation issues.

Handle Multi-Page Content

Long content often exceeds one page. For scroll views, render page by page by shifting content offset.

swift
1import UIKit
2
3func pdfFromScrollView(_ scrollView: UIScrollView, pageSize: CGSize) -> Data {
4    let renderer = UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, size: pageSize))
5    let originalOffset = scrollView.contentOffset
6
7    let data = renderer.pdfData { context in
8        let totalHeight = scrollView.contentSize.height
9        var y: CGFloat = 0
10
11        while y < totalHeight {
12            context.beginPage()
13            scrollView.contentOffset = CGPoint(x: 0, y: y)
14            scrollView.layer.render(in: context.cgContext)
15            y += pageSize.height
16        }
17    }
18
19    scrollView.contentOffset = originalOffset
20    return data
21}

This simple strategy works well for report-like vertical content.

Add Metadata and Control Output Size

UIGraphicsPDFRendererFormat supports metadata dictionary values like title and author.

swift
1let format = UIGraphicsPDFRendererFormat()
2format.documentInfo = [
3    kCGPDFContextTitle as String: "Monthly Report",
4    kCGPDFContextAuthor as String: "MyApp"
5]

To reduce file size, avoid unnecessarily large bitmap assets in the source view.

Async Workflows and Main-Thread Safety

If export is triggered from async code, perform UIKit rendering on main actor, then handle file I/O as needed.

swift
1Task { @MainActor in
2    prepareForExport(myView)
3    let data = pdfData(from: myView)
4    let url = try savePDF(data, fileName: "export.pdf")
5    print(url)
6}

Keeping rendering on main thread avoids subtle UI crashes.

Cleanup and Security

If PDFs contain sensitive user information, define retention rules.

  • Store only as long as needed.
  • Delete temporary files after sharing.
  • Avoid exposing private document paths in logs.

Secure file handling is part of production export quality.

Common Pitfalls

  • Rendering before layout is complete. Fix: call layoutIfNeeded before PDF generation.
  • Running UIKit rendering on background thread. Fix: do rendering on main thread or main actor.
  • Assuming long scroll content fits one page. Fix: implement pagination for multi-page exports.
  • Leaving temporary sensitive PDFs on disk. Fix: add explicit cleanup flow after sharing.
  • Ignoring iPad presentation rules for activity controller. Fix: configure popover anchor where required.

Summary

  • Use UIGraphicsPDFRenderer to capture UIView content as PDF data.
  • Ensure layout is finalized before rendering.
  • Save to app storage and share with activity controller.
  • Add pagination for long content and metadata for document quality.
  • Treat file cleanup and thread safety as first-class concerns.

Course illustration
Course illustration

All Rights Reserved.