Communitygithub.com

PDFKit

Muestra y manipula documentos PDF usando PDFKit. Útil para incrustar PDFView, crear o modificar PDFDocument, agregar anotaciones, extraer texto, navegar páginas, generar miniaturas, rellenar formularios PDF o integrar PDFView en SwiftUI.

¿Qué es PDFKit?

PDFKit es un skill que proporciona una guía completa para trabajar con documentos PDF en aplicaciones iOS, iPadOS, macOS, tvOS y visionOS utilizando el framework PDFKit de Apple. El skill cubre desde la visualización básica de PDFs con PDFView hasta la manipulación avanzada de documentos, incluyendo la carga de documentos protegidos con contraseña, la navegación entre páginas con historial, la búsqueda de texto tanto síncrona como asíncrona, y la extracción de texto de páginas completas o regiones específicas. También incluye una sección detallada sobre cómo agregar, modificar y eliminar anotaciones como resaltados, notas adhesivas, texto libre, enlaces y formas geométricas, así como la generación de miniaturas de páginas. Además, proporciona ejemplos prácticos de integración con SwiftUI mediante UIViewRepresentable y cubre patrones de superposición de páginas (PDFPageOverlayViewProvider) para iOS 16+. El skill incluye una sección de errores comunes y una lista de verificación para revisión de código, lo que lo hace ideal para desarrolladores que necesitan implementar funcionalidades PDF de manera robusta y eficiente en sus aplicaciones Apple.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/JordanCoin/ios-skills-collection/tree/HEAD/skills/dpearson2699--pdfkit

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

¿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

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

ModoComportamiento
.singlePageUna página a la vez
.singlePageContinuousPáginas apiladas verticalmente, desplazables
.twoUpDos páginas lado a lado
.twoUpContinuousDos 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

SubtipoConstantePropósito
Resaltado.highlightMarcado de texto (resaltado amarillo)
Subrayado.underlineMarcado de texto (subrayado)
Tachado.strikeOutMarcado de texto (tachado)
Texto.textIcono de nota adhesiva
Texto libre.freeTextBloque de texto en línea
Tinta.inkTrazos de dibujo a mano alzada
Enlace.linkURL o destino de página
Línea.lineLínea recta con extremos
Cuadrado.squareForma rectangular
Círculo.circleForma elíptica
Sello.stampSello de goma (Aprobado, etc.)
Widget.widgetElemento 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 PDFDocument usa enlace opcional, no desempaquetado forzado
  • pdfView.autoScales = true configurado para una visualización inicial adecuada
  • Índices de página verificados contra pageCount antes del acceso
  • displayMode y displayDirection configurados 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 !== en updateUIView
  • Se observa la notificación PDFViewPageChanged para el seguimiento de página
  • PDFThumbnailView.pdfView vinculado al PDFView principal
  • La búsqueda de documentos grandes usa beginFindString asíncrono con delegado
  • Los documentos guardados usan write(to:withOptions:) cuando se necesita cifrado

Referencias

Individual skills in this repo

This repo contains 11 individual skills — each has its own dedicated page.

JordanCoin/ios-skills-collection

Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries. Use when the user asks about GitHub issues, pull requests, workflows, or wants to interact with GitHub repositories from the command line — including tasks like check CI status, create PR, list issues, or query the GitHub API.

JordanCoin/ios-skills-collection

Create media playback experiences using AVKit. Use when adding video players with AVPlayerViewController, enabling Picture-in-Picture, routing media with AirPlay, using SwiftUI VideoPlayer views, configuring transport controls, displaying subtitles and closed captions, or integrating AVFoundation playback with system UI.

JordanCoin/ios-skills-collection

Integrate and optimize Core ML models in iOS apps for on-device machine learning inference. Covers model loading (.mlmodelc, .mlpackage), predictions with auto-generated classes and MLFeatureProvider, compute unit configuration (CPU, GPU, Neural Engine), MLTensor, VNCoreMLRequest, MLComputePlan, multi-model pipelines, and deployment strategies. Use when loading Core ML models, making predictions, configuring compute units, or profiling model performance.

JordanCoin/ios-skills-collection

Implement, review, or improve maps and location features in iOS/macOS apps using MapKit and CoreLocation. Use when working with Map views, annotations, markers, polylines, user location tracking, geocoding, reverse geocoding, search/autocomplete, directions and routes, geofencing, region monitoring, CLLocationUpdate async streams, or location authorization flows. Also use when working with maps, coordinates, addresses, places, directions, distance calculations, or location-based features in Swift apps.

JordanCoin/ios-skills-collection

Implement, review, or improve in-app tips and onboarding using Apple's TipKit framework. Use when adding feature discovery tooltips, onboarding flows, contextual tips, first-run experiences, coach marks, or working with Tip protocol, TipView, popoverTip, tip rules, tip events, or feature education UI.

JordanCoin/ios-skills-collection

When the user wants to optimize their Google Play Store listing — title, short description, full description, keywords, ratings, or Play Store-specific features. Use when the user mentions "Google Play", "Android", "Play Store", "Play Console", "short description", "full description indexed", "Google Play ASO", or wants Google Play-specific keyword, creative, or ratings strategy. For iOS App Store optimization, see aso-audit and metadata-optimization.

JordanCoin/ios-skills-collection

When the user wants to implement, optimize, or use App Clips for app discovery and conversion. Use when the user mentions "App Clip", "app clip code", "mini app", "instant app", "App Clip card", "App Clip link", "no download required", "instant experience", or wants to understand how App Clips appear in App Store search. For general App Store discoverability, see aso-audit. For marketing campaigns, see ua-campaign.

JordanCoin/ios-skills-collection

When the user wants to plan a launch strategy for a new app or major update. Also use when the user mentions "app launch", "launch plan", "launch checklist", "pre-launch", "launch day", or "how to launch my app". For ongoing ASO after launch, see aso-audit. For paid acquisition during launch, see ua-campaign.

JordanCoin/ios-skills-collection

When the user wants to analyze their own app's actual performance data from App Store Connect — real downloads, revenue, IAP, subscriptions, trials, or country breakdowns synced via Appeeky Connect. Use when the user asks about "my downloads", "my revenue", "how is my app performing", "ASC data", "sales and trends", "my subscription numbers", "App Store Connect metrics", or wants to compare periods or top markets. For third-party app estimates, see app-analytics. For subscription analytics depth, see monetization-strategy.

JordanCoin/ios-skills-collection

When the user wants a full ASO health audit, review their App Store listing quality, or diagnose why their app isn't ranking. Also use when the user mentions "ASO audit", "ASO score", "why am I not ranking", "listing review", or "optimize my app store page". For keyword-specific research, see keyword-research. For metadata writing, see metadata-optimization.

JordanCoin/ios-skills-collection

Always use when working on any iOS, macOS, Swift, SwiftUI, Xcode, or Apple platform project. Routes to the correct specialized skills based on development phase and task context. This collection contains 210 skills from 28 authors covering the full iOS lifecycle.

Skills relacionados