Generación de informes PDF en Swift (iOS/macOS)
La creación de documentos PDF en las plataformas de Apple es una de las tareas clave en el desarrollo de aplicaciones empresariales, informes financieros o sistemas de gestión documental. A diferencia del stack web, donde se utilizan muchas bibliotecas de terceros, en el ecosistema Swift para trabajar con PDF existen tanto potentes frameworks integrados como soluciones especializadas de terceros. En este artículo, analizaremos en detalle todas las herramientas principales para la generación de informes PDF en Swift para iOS y macOS.
Frameworks integrados de Apple
Apple proporciona dos formas principales de crear documentos PDF: UIGraphicsPDFRenderer (para UIKit) y PDFKit (para trabajar con PDF existentes). También en macOS está disponible NSGraphicsContext con soporte para PDF.
UIGraphicsPDFRenderer (iOS 10+)
Esta es la herramienta principal para generar PDF a partir de contenido UIKit. Permite dibujar texto, imágenes, tablas y gráficos arbitrarios en el contexto de una página PDF.
import UIKit
func generateReport(data: String) -> Data { let pageSize = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4 let renderer = UIGraphicsPDFRenderer(bounds: pageSize) return renderer.pdfData { context in context.beginPage() // Título let title = "Informe de ventas" let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.boldSystemFont(ofSize: 24), .foregroundColor: UIColor.darkGray ] title.draw(at: CGPoint(x: 50, y: 50), withAttributes: attributes) // Contenido let textAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 14) ] data.draw(at: CGPoint(x: 50, y: 100), withAttributes: textAttributes) // Línea separadora context.cgContext.setStrokeColor(UIColor.lightGray.cgColor) context.cgContext.setLineWidth(1) context.cgContext.move(to: CGPoint(x: 50, y: 90)) context.cgContext.addLine(to: CGPoint(x: 545, y: 90)) context.cgContext.strokePath() }}PDFKit (iOS 11+, macOS 10.13+)
PDFKit es un framework de más alto nivel que permite no solo crear, sino también editar PDF existentes. Soporta anotaciones, formularios, marcadores y trabajo con documentos de varias páginas.
import PDFKit
func createPDFWithText() -> PDFDocument { let page = PDFPage() let pdfDocument = PDFDocument() // Creamos una página con texto let text = "PDFKit permite añadir fácilmente texto y anotaciones" let textAnnotation = PDFAnnotation( bounds: CGRect(x: 50, y: 700, width: 500, height: 100), forType: .freeText, withProperties: nil ) textAnnotation.contents = text textAnnotation.font = UIFont.systemFont(ofSize: 18) page.addAnnotation(textAnnotation) pdfDocument.insert(page, at: 0) return pdfDocument}Bibliotecas de terceros para Swift
Aunque las herramientas integradas cubren la mayoría de las tareas, existen situaciones donde se necesita funcionalidad especializada: trabajo con plantillas, exportación a PDF desde SwiftUI o soporte para maquetación compleja.
SwiftUI y PDF (iOS 14+, macOS 11+)
A partir de iOS 14, es posible convertir vistas SwiftUI a PDF usando ImageRenderer:
import SwiftUI
struct ReportView: View { var body: some View { VStack(alignment: .leading) { Text("Informe mensual") .font(.largeTitle) .foregroundColor(.blue) Text("Datos de agosto 2024") .font(.headline) Divider() Text("Ingresos: 1 234 567 ₽") .font(.body) } .padding() }}
func generatePDFFromSwiftUI() -> Data { let vie