Generación de PDF en Swift (iOS/macOS): de lo simple a lo complejo
La creación de documentos PDF es una de las tareas comunes en el desarrollo móvil y de escritorio. En las plataformas de Apple (iOS/macOS), las herramientas integradas permiten generar PDF de calidad sin bibliotecas de terceros. En este artículo, analizaremos tres enfoques principales: UIGraphicsPDFRenderer (moderno y simple), PDFKit (para trabajar con PDF existentes) y Core Graphics (para control total). Todos los ejemplos están escritos en Swift y son adecuados tanto para iOS como para macOS (con cambios mínimos).
1. UIGraphicsPDFRenderer — el estándar moderno
UIGraphicsPDFRenderer apareció en iOS 10 y macOS 10.12. Proporciona una API de alto nivel para crear PDF de varias páginas. Las principales ventajas: trabajo automático con el contexto, soporte de metadatos y facilidad de uso.
Ejemplo básico: crear un PDF con texto
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 // Primera página context.beginPage() let text = "¡Hola, mundo PDF!" let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 24), .foregroundColor: UIColor.black ] text.draw(at: CGPoint(x: 50, y: 50), withAttributes: attributes) // Segunda página context.beginPage() let secondText = "Esta es la segunda página" secondText.draw(at: CGPoint(x: 50, y: 50), withAttributes: attributes) } return data}
// Guardar en archivoif 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 guardado: \\(pdfURL)")}Ejemplo avanzado: tabla e imagen
func generateInvoicePDF() -> Data { let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 612, height: 792)) return renderer.pdfData { context in context.beginPage() // Dibujar logotipo (si existe) if let logo = UIImage(named: "logo") { logo.draw(in: CGRect(x: 50, y: 50, width: 100, height: 50)) } // Título let titleAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.boldSystemFont(ofSize: 28), .foregroundColor: UIColor.darkGray ] "FACTURA Nº123".draw(at: CGPoint(x: 400, y: 50), withAttributes: titleAttributes) // Tabla let items = [("Producto", "Precio"), ("Portátil", "1200$"), ("Ratón", "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 — trabajo con PDF existentes y anotaciones
PDFKit es un framework más potente, que