Génération de PDF en Swift (iOS/macOS) : UIGraphicsPDFRenderer, PDFKit et Core Graphics

Formateur Python en ligne pour débutants

Apprenez Python facilement sans surcharge théorique. Résolvez des tâches pratiques avec vérification automatique et écrivez du code directement dans le navigateur.

Start Course

Génération de PDF en Swift (iOS/macOS) : du simple au complexe



La création de documents PDF est une tâche courante dans le développement mobile et de bureau. Sur les plateformes Apple (iOS/macOS), les outils intégrés permettent de générer des PDF de qualité sans bibliothèques tierces. Dans cet article, nous aborderons trois approches principales : UIGraphicsPDFRenderer (moderne et simple), PDFKit (pour travailler avec des PDF existants) et Core Graphics (pour un contrôle total). Tous les exemples sont écrits en Swift et conviennent aussi bien pour iOS que pour macOS (avec des modifications minimes).



1. UIGraphicsPDFRenderer — le standard moderne



UIGraphicsPDFRenderer est apparu dans iOS 10 et macOS 10.12. Il fournit une API de haut niveau pour créer des PDF multipages. Les principaux avantages : gestion automatique du contexte, prise en charge des métadonnées et simplicité d'utilisation.



Exemple de base : création d'un PDF avec du texte



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 // Première page context.beginPage() let text = "Bonjour le monde PDF !" let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 24), .foregroundColor: UIColor.black ] text.draw(at: CGPoint(x: 50, y: 50), withAttributes: attributes) // Deuxième page context.beginPage() let secondText = "Ceci est la deuxième page" secondText.draw(at: CGPoint(x: 50, y: 50), withAttributes: attributes) } return data}

// Sauvegarde dans un fichierif 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 sauvegardé : \\(pdfURL)")}


Exemple avancé : tableau et image



func generateInvoicePDF() -> Data {    let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 612, height: 792))        return renderer.pdfData { context in        context.beginPage()                // Dessiner le logo (s'il existe)        if let logo = UIImage(named: "logo") {            logo.draw(in: CGRect(x: 50, y: 50, width: 100, height: 50))        }                // Titre        let titleAttributes: [NSAttributedString.Key: Any] = [            .font: UIFont.boldSystemFont(ofSize: 28),            .foregroundColor: UIColor.darkGray        ]        "FACTURE N°123".draw(at: CGPoint(x: 400, y: 50), withAttributes: titleAttributes)                // Tableau        let items = [("Produit", "Prix"), ("Ordinateur portable", "1200$"), ("Souris", "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        }                // Total        let totalAttributes: [NSAttributedString.Key: Any] = [            .font: UIFont.boldSystemFont(ofSize: 18),            .foregroundColor: UIColor.red        ]        "Total : 1225$".draw(at: CGPoint(x: 350, y: yPosition + 20), withAttributes: totalAttributes)    }}


2. PDFKit — travailler avec des PDF existants et des annotations



PDFKit est un framework plus puissant, qui

Recommendations