How to Convert Text Content into a PDF File in Swift (iOS – Swift 5+)

Inwizards-blog-img

Creating PDF files dynamically in an iOS application is a common requirement for features like invoices, reports, user-generated documents, or downloadable content. In this guide, you’ll learn how to convert text content into a PDF file in Swift using modern iOS APIs (Swift 5+).

This tutorial demonstrates how to:

  • Generate a PDF file programmatically
  • Render text content inside a PDF
  • Save the PDF locally on the device
  • Access the generated PDF for sharing or preview

Why Generate PDFs in an iOS App?

PDF generation is useful for many real-world scenarios, including:

  • Exporting reports or analytics
  • Generating invoices or receipts
  • Saving form data as documents
  • Sharing user-generated content
  • Offline document storage

iOS provides powerful native APIs that allow you to generate PDFs without third-party libraries, ensuring better performance and long-term stability.

Prerequisites

Before you start, make sure you have:

  • Xcode 14 or later
  • Swift 5+
  • Basic knowledge of UIKit
  • An iOS project using UIKit (not SwiftUI)

Project Setup

  1. Open Xcode and create a new Single View App

  2. Choose UIKit and Swift

  3. Name the project GeneratePDFDemo

UI Elements

Add the following to your storyboard:

  • A UITextView (for user input)
  • A UIButton labeled “Generate PDF”

Connect:

  • UITextView → IBOutlet (textView)
  • UIButton → IBAction (generatePDF)

Modern Way to Create PDFs in Swift

Starting with iOS 10, Apple introduced UIGraphicsPDFRenderer, which is the recommended way to create PDFs.

Why Use UIGraphicsPDFRenderer?

  • Better performance
  • Cleaner API
  • Supports modern Swift
  • Automatically manages PDF contexts

Step 1: Create the PDF File URL

func getDocumentsDirectory() -> URL {

FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

}

 

This ensures the PDF is stored safely inside the app’s sandbox.

Step 2: Generate the PDF

func generatePDF(from text: String) -> URL {

let pdfURL = getDocumentsDirectory().appendingPathComponent(“GeneratedText.pdf”)

 

let pageRect = CGRect(x: 0, y: 0, width: 595, height: 842) // A4 size

let renderer = UIGraphicsPDFRenderer(bounds: pageRect)

 

renderer.writePDF(to: pdfURL) { context in

context.beginPage()

 

let textRect = CGRect(x: 20, y: 40, width: pageRect.width – 40, height: pageRect.height – 80)

let paragraphStyle = NSMutableParagraphStyle()

paragraphStyle.lineSpacing = 6

 

let attributes: [NSAttributedString.Key: Any] = [

.font: UIFont.systemFont(ofSize: 16),

.paragraphStyle: paragraphStyle

]

 

text.draw(in: textRect, withAttributes: attributes)

}

 

return pdfURL

}

 

Step 3: Connect Button Action

@IBAction func generatePDF(_ sender: UIButton) {

let text = textView.text ?? “”

let pdfURL = generatePDF(from: text)

print(“PDF saved at:”, pdfURL)

}

 

Once tapped, this button generates a PDF containing the text entered by the user.

Step 4: Preview or Share the PDF (Optional)

You can preview or share the PDF using UIActivityViewController:

let activityVC = UIActivityViewController(activityItems: [pdfURL], applicationActivities: nil)

present(activityVC, animated: true)

 

Common Customizations

Add Images to the PDF

let image = UIImage(named: “logo”)

image?.draw(in: CGRect(x: 200, y: 100, width: 150, height: 150))

 

Change Font or Colors

Modify the attributes dictionary:

.font: UIFont.boldSystemFont(ofSize: 18)

.foregroundColor: UIColor.darkGray

 

Multiple Pages

Call context.beginPage() again to create a new page.

Where Is the PDF Stored?

The generated PDF is saved in:

App Sandbox → Documents Directory

 

You can access it via:

  • Finder (for simulator)
  • Files app (if shared)
  • Programmatic upload to a server

Common Issues & Tips

Text getting cut off?
→ Increase page height or implement pagination.

Large text content?
→ Split content across multiple pages.

Performance concerns?
→ Avoid generating PDFs on the main thread for very large documents.

FAQs

Q: Is this compatible with SwiftUI?
Yes. You can move the PDF logic into a separate class and call it from SwiftUI.

Q: Can I upload the PDF to a server?
Yes. Use URLSession after generating the file.

Q: Is UIGraphicsPDFRenderer production-ready?
Absolutely. It is Apple’s recommended API.

Q: Can I add tables or layouts?
Yes, but you must manually calculate positions or use Core Text.

Conclusion

Generating PDFs in iOS using Swift is both powerful and efficient when using modern APIs like UIGraphicsPDFRenderer. With just a few lines of code, you can transform user input into professional, shareable documents—all without relying on third-party libraries.

If you’re building invoice systems, reporting tools, or document-based iOS apps, this approach provides a scalable and future-proof solution.

How to Convert Text Content into a PDF File in Swift (iOS – Swift 5+)

Post navigation


1 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x