PDF-Erstellung in Swift (iOS/macOS): UIGraphicsPDFRenderer, PDFKit und Core Graphics

Online Python-Trainer für Anfänger

Lernen Sie Python einfach ohne theoretische Überlastung. Lösen Sie praktische Aufgaben mit automatischer Überprüfung und schreiben Sie Code direkt im Browser.

Kurs starten

PDF-Erstellung in Swift (iOS/macOS): vom Einfachen zum Komplexen



Die Erstellung von PDF-Dokumenten ist eine häufige Aufgabe in der mobilen und Desktop-Entwicklung. Auf Apple-Plattformen (iOS/macOS) ermöglichen integrierte Werkzeuge die Generierung hochwertiger PDFs ohne externe Bibliotheken. In diesem Artikel betrachten wir drei Hauptansätze: UIGraphicsPDFRenderer (modern und einfach), PDFKit (für die Arbeit mit vorhandenen PDFs) und Core Graphics (für vollständige Kontrolle). Alle Beispiele sind in Swift geschrieben und eignen sich sowohl für iOS als auch für macOS (mit minimalen Änderungen).



1. UIGraphicsPDFRenderer – der moderne Standard



UIGraphicsPDFRenderer wurde in iOS 10 und macOS 10.12 eingeführt. Er bietet eine hochwertige API zur Erstellung mehrseitiger PDFs. Hauptvorteile: automatische Kontextverwaltung, Unterstützung für Metadaten und einfache Handhabung.



Basisbeispiel: PDF mit Text erstellen



import UIKit

func generateSimplePDF() -> Data? { let pageWidth: CGFloat = 612 // A4 let pageHeight: CGFloat = 792 let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)) let data = renderer.pdfData { context in // Erste Seite context.beginPage() let text = "Hallo, PDF-Welt!" let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 24), .foregroundColor: UIColor.black ] text.draw(at: CGPoint(x: 50, y: 50), withAttributes: attributes) // Zweite Seite context.beginPage() let secondText = "Dies ist die zweite Seite" secondText.draw(at: CGPoint(x: 50, y: 50), withAttributes: attributes) } return data}

// In Datei speichernif let pdfData = generateSimplePDF() { let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let pdfURL = documentsPath.appendingPathComponent("sample.pdf") try? pdfData.write(to: pdfURL) print("PDF gespeichert: \\(pdfURL)")


Fortgeschrittenes Beispiel: Tabelle und Bild



func generateInvoicePDF() -> Data {    let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 612, height: 792))        return renderer.pdfData { context in        context.beginPage()                // Logo zeichnen (falls vorhanden)        if let logo = UIImage(named: "logo") {            logo.draw(in: CGRect(x: 50, y: 50, width: 100, height: 50))        }                // Überschrift        let titleAttributes: [NSAttributedString.Key: Any] = [            .font: UIFont.boldSystemFont(ofSize: 28),            .foregroundColor: UIColor.darkGray        ]        "RECHNUNG Nr. 123".draw(at: CGPoint(x: 400, y: 50), withAttributes: titleAttributes)                // Tabelle        let items = [("Artikel", "Preis"), ("Laptop", "1200$"), ("Maus", "25$")]        var yPosition: CGFloat = 200                for (name, price) in items {            let nameAttributes: [NSAttributedString.Key: Any] = [                .font: UIFont.systemFont(ofSize: 14),                .foregroundColor: UIColor.black            ]            name.draw(at: CGPoint(x: 100, y: yPosition), withAttributes: nameAttributes)            price.draw(at: CGPoint(x: 400, y: yPosition), withAttributes: nameAttributes)            yPosition += 30        }                // Gesamtsumme        let totalAttributes: [NSAttributedString.Key: Any] = [            .font: UIFont.boldSystemFont(ofSize: 18),            .foregroundColor: UIColor.red        ]        "Gesamtsumme: 1225$".draw(at: CGPoint(x: 350, y: yPosition + 20), withAttributes: totalAttributes)    }}


2. PDFKit – Arbeit mit vorhandenen PDFs und Annotationen



PDFKit ist ein leistungsfähigeres Framework, das

Empfehlungen