¿Qué hace PDFKit?
Muestra, navega, busca, anota y manipula documentos PDF con
PDFView, PDFDocument, PDFPage, PDFAnnotation y PDFSelection.
Apunta a Swift 6.3 / iOS 26+.
Contenido
- Configuración
- Mostrar PDFs
- Cargar Documentos
- Navegación de Páginas
- Búsqueda y Selección de Texto
- Anotaciones
- Miniaturas
- Integración con SwiftUI
- Errores Comunes
- Lista de Verificación
- Referencias
Configuración
PDFKit no requiere entitlements ni entradas en Info.plist.
import PDFKit
Disponibilidad de plataforma: iOS 11+, iPadOS 11+, Mac Catalyst 13.1+, macOS 10.4+, tvOS 11+, visionOS 1.0+.
Mostrar PDFs
PDFView es una subclase de UIView que renderiza contenido PDF, maneja zoom,
desplazamiento, selección de texto y navegación de páginas de forma predeterminada.
import PDFKit
import UIKit
class PDFViewController: UIViewController {
let pdfView = PDFView()
override func viewDidLoad() {
super.viewDidLoad()
pdfView.frame = view.bounds
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(pdfView)
pdfView.autoScales = true
pdfView.displayMode = .singlePageContinuous
pdfView.displayDirection = .vertical
if let url = Bundle.main.url(forResource: "sample", withExtension: "pdf") {
pdfView.document = PDFDocument(url: url)
}
}
}
Modos de Visualización
| Modo | Comportamiento |
|---|---|
.singlePage | Una página a la vez |
.singlePageContinuous | Páginas apiladas verticalmente, desplazables |
.twoUp | Dos páginas lado a lado |
.twoUpContinuous | Dos páginas con desplazamiento continuo |
Escalado y Apariencia
pdfView.autoScales = true
pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
pdfView.maxScaleFactor = 4.0
pdfView.displaysPageBreaks = true
pdfView.pageShadowsEnabled = true
pdfView.interpolationQuality = .high
Cargar Documentos
PDFDocument se carga desde una URL, Data, o se puede crear vacío.
let fileDoc = PDFDocument(url: fileURL)
let dataDoc = PDFDocument(data: pdfData)
let emptyDoc = PDFDocument()
PDFs Protegidos con Contraseña
guard let document = PDFDocument(url: url) else { return }
if document.isLocked {
if !document.unlock(withPassword: userPassword) {
// Mostrar diálogo de contraseña
}
}
Guardado y Manipulación de Páginas
document.write(to: outputURL)
document.write(to: outputURL, withOptions: [
.ownerPasswordOption: "ownerPass", .userPasswordOption: "userPass"
])
let data = document.dataRepresentation()
// Páginas (base 0)
let count = document.pageCount
document.insert(PDFPage(), at: count)
document.removePage(at: 2)
document.exchangePage(at: 0, withPageAt: 3)
Navegación de Páginas
PDFView proporciona navegación integrada con seguimiento de historial.
// Ir a una página específica
if let page = pdfView.document?.page(at: 5) {
pdfView.go(to: page)
}
// Navegación secuencial
pdfView.goToNextPage(nil)
pdfView.goToPreviousPage(nil)
pdfView.goToFirstPage(nil)
pdfView.goToLastPage(nil)
// Verificar estado de navegación
if pdfView.canGoToNextPage { /* ... */ }
// Navegación por historial
if pdfView.canGoBack { pdfView.goBack(nil) }
// Ir a un punto específico en una página
let destination = PDFDestination(page: page, at: CGPoint(x: 0, y: 500))
pdfView.go(to: destination)
Observar Cambios de Página
NotificationCenter.default.addObserver(
self, selector: #selector(pageChanged),
name: .PDFViewPageChanged, object: pdfView
)
@objc func pageChanged(_ notification: Notification) {
guard let page = pdfView.currentPage,
let doc = pdfView.document else { return }
let index = doc.index(for: page)
pageLabel.text = "Página \(index + 1) de \(doc.pageCount)"
}
Búsqueda y Selección de Texto
Búsqueda Síncrona
let results: [PDFSelection] = document.findString(
"término de búsqueda", withOptions: [.caseInsensitive]
)
Búsqueda Asíncrona
Usa PDFDocumentDelegate para búsquedas en segundo plano en documentos grandes.
Implementa didMatchString(_:) para recibir cada coincidencia y
documentDidEndDocumentFind(_:) para la finalización.
Búsqueda Incremental e Interacción de Buscar
// Encontrar la siguiente coincidencia desde la selección actual
let next = document.findString("término", fromSelection: current, withOptions: [.caseInsensitive])
// Barra de búsqueda del sistema (iOS 16+)
pdfView.isFindInteractionEnabled = true
Extracción de Texto
let fullText = document.string // Documento completo
let pageText = document.page(at: 0)?.string // Página individual
let attributed = document.page(at: 0)?.attributedString // Con formato
// Extracción basada en región
if let page = document.page(at: 0) {
let selection = page.selection(for: CGRect(x: 50, y: 50, width: 400, height: 200))
let text = selection?.string
}
Resaltado de Resultados de Búsqueda
let results = document.findString("importante", withOptions: [.caseInsensitive])
for selection in results { selection.color = .yellow }
pdfView.highlightedSelections = results
if let first = results.first {
pdfView.setCurrentSelection(first, animate: true)
pdfView.go(to: first)
}
Anotaciones
Las anotaciones se crean con PDFAnnotation(bounds:forType:withProperties:)
y se añaden a una PDFPage.
Anotación de Resaltado
func addHighlight(to page: PDFPage, selection: PDFSelection) {
let highlight = PDFAnnotation(
bounds: selection.bounds(for: page),
forType: .highlight, withProperties: nil
)
highlight.color = UIColor.yellow.withAlphaComponent(0.5)
page.addAnnotation(highlight)
}
Anotación de Nota de Texto
let note = PDFAnnotation(
bounds: CGRect(x: 100, y: 700, width: 30, height: 30),
forType: .text, withProperties: nil
)
note.contents = "Esta es una nota adhesiva."
note.color = .systemYellow
note.iconType = .comment
page.addAnnotation(note)
Anotación de Texto Libre
let freeText = PDFAnnotation(
bounds: CGRect(x: 50, y: 600, width: 300, height: 40),
forType: .freeText, withProperties: nil
)
freeText.contents = "Comentario añadido"
freeText.font = UIFont.systemFont(ofSize: 14)
freeText.fontColor = .darkGray
page.addAnnotation(freeText)
Anotación de Enlace
let link = PDFAnnotation(
bounds: CGRect(x: 50, y: 500, width: 200, height: 20),
forType: .link, withProperties: nil
)
link.url = URL(string: "https://example.com")
page.addAnnotation(link)
// Enlace a página interna
link.destination = PDFDestination(page: targetPage, at: .zero)
Eliminar Anotaciones
for annotation in page.annotations {
page.removeAnnotation(annotation)
}
Referencia de Subtipos de Anotaciones
| Subtipo | Constante | Propósito |
|---|---|---|
| Resaltado | .highlight | Marcado de texto (resaltado amarillo) |
| Subrayado | .underline | Marcado de texto (subrayado) |
| Tachado | .strikeOut | Marcado de texto (tachado) |
| Texto | .text | Icono de nota adhesiva |
| Texto libre | .freeText | Bloque de texto en línea |
| Tinta | .ink | Trazos de dibujo a mano alzada |
| Enlace | .link | URL o destino de página |
| Línea | .line | Línea recta con extremos |
| Cuadrado | .square | Forma rectangular |
| Círculo | .circle | Forma elíptica |
| Sello | .stamp | Sello de goma (Aprobado, etc.) |
| Widget | .widget | Elemento de formulario (campo de texto, casilla de verificación) |
Miniaturas
PDFThumbnailView
PDFThumbnailView muestra una tira de miniaturas de páginas vinculada a un PDFView.
let thumbnailView = PDFThumbnailView()
thumbnailView.pdfView = pdfView
thumbnailView.thumbnailSize = CGSize(width: 60, height: 80)
thumbnailView.layoutMode = .vertical
thumbnailView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(thumbnailView)
Generar Miniaturas Programáticamente
let thumbnail = page.thumbnail(of: CGSize(width: 120, height: 160), for: .mediaBox)
// Todas las páginas
let thumbnails = (0..<document.pageCount).compactMap {
document.page(at: $0)?.thumbnail(of: CGSize(width: 120, height: 160), for: .mediaBox)
}
Integración con SwiftUI
Envuelve PDFView en un UIViewRepresentable para SwiftUI.
import SwiftUI
import PDFKit
struct PDFKitView: UIViewRepresentable {
let document: PDFDocument
func makeUIView(context: Context) -> PDFView {
let pdfView = PDFView()
pdfView.autoScales = true
pdfView.displayMode = .singlePageContinuous
pdfView.document = document
return pdfView
}
func updateUIView(_ pdfView: PDFView, context: Context) {
if pdfView.document !== document {
pdfView.document = document
}
}
}
Uso
struct DocumentScreen: View {
let url: URL
var body: some View {
if let document = PDFDocument(url: url) {
PDFKitView(document: document)
.ignoresSafeArea()
} else {
ContentUnavailableView("No se pudo cargar el PDF", systemImage: "doc.questionmark")
}
}
}
Para envoltorios interactivos con seguimiento de página, detección de toques en anotaciones y patrones de coordinador, consulta references/pdfkit-patterns.md.
Superposiciones de Página (iOS 16+)
PDFPageOverlayViewProvider coloca vistas de UIKit sobre páginas individuales
para controles interactivos o renderizado personalizado más allá de las anotaciones estándar.
class OverlayProvider: NSObject, PDFPageOverlayViewProvider {
func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? {
let overlay = UIView()
// Añadir subvistas personalizadas
return overlay
}
}
pdfView.pageOverlayViewProvider = overlayProvider
Errores Comunes
NO HACER: Forzar el desempaquetado del inicializador de PDFDocument
PDFDocument(url:) y PDFDocument(data:) son inicializadores que pueden fallar.
// INCORRECTO
let document = PDFDocument(url: url)!
// CORRECTO
guard let document = PDFDocument(url: url) else { return }
NO HACER: Olvidar autoScales en PDFView
Sin autoScales, el PDF se renderiza a su resolución nativa.
// INCORRECTO
pdfView.document = document
// CORRECTO
pdfView.autoScales = true
pdfView.document = document
NO HACER: Ignorar el sistema de coordenadas PDF en anotaciones
Las coordenadas de página PDF tienen el origen en la parte inferior izquierda con Y incrementándose hacia arriba, lo opuesto a UIKit.
// INCORRECTO: Coordenadas UIKit
let bounds = CGRect(x: 50, y: 50, width: 200, height: 30)
// CORRECTO: Coordenadas PDF (origen inferior izquierdo)
let pageBounds = page.bounds(for: .mediaBox)
let pdfY = pageBounds.height - 50 - 30
let bounds = CGRect(x: 50, y: pdfY, width: 200, height: 30)
NO HACER: Modificar anotaciones en un hilo secundario
Las clases de PDFKit no son seguras para subprocesos.
// INCORRECTO
DispatchQueue.global().async { page.addAnnotation(annotation) }
// CORRECTO
DispatchQueue.main.async { page.addAnnotation(annotation) }
NO HACER: Comparar PDFDocument con == en UIViewRepresentable
PDFDocument es un tipo de referencia. Usa identidad (!==).
// INCORRECTO: Siempre reemplaza el documento
func updateUIView(_ pdfView: PDFView, context: Context) {
pdfView.document = document
}
// CORRECTO
func updateUIView(_ pdfView: PDFView, context: Context) {
if pdfView.document !== document {
pdfView.document = document
}
}
Lista de Verificación
- El inicializador
PDFDocumentusa enlace opcional, no desempaquetado forzado -
pdfView.autoScales = trueconfigurado para una visualización inicial adecuada - Índices de página verificados contra
pageCountantes del acceso -
displayModeydisplayDirectionconfigurados para coincidir con el diseño - Las anotaciones usan el espacio de coordenadas PDF (origen inferior izquierdo, Y hacia arriba)
- Todas las mutaciones de PDFKit ocurren en el hilo principal
- PDFs protegidos con contraseña manejados con
isLocked/unlock(withPassword:) - El envoltorio SwiftUI usa verificación de identidad
!==enupdateUIView - Se observa la notificación
PDFViewPageChangedpara el seguimiento de página -
PDFThumbnailView.pdfViewvinculado alPDFViewprincipal - La búsqueda de documentos grandes usa
beginFindStringasíncrono con delegado - Los documentos guardados usan
write(to:withOptions:)cuando se necesita cifrado
Referencias
- Patrones extendidos (formularios, marcas de agua, fusión, impresión, superposiciones, esquemas, dibujo personalizado): references/pdfkit-patterns.md
- Framework PDFKit
- PDFView
- PDFDocument
- PDFPage
- PDFAnnotation
- PDFSelection
- PDFThumbnailView
- PDFPageOverlayViewProvider
- Adding Widgets to a PDF Document
- Adding Custom Graphics to a PDF