SkillsGrove
SkillsGrove/Documents bureautiques/TalissonVitorino/kmp-ios-skills/pdfkit

pdfkit

Installation

$npx skills add https://github.com/TalissonVitorino/kmp-ios-skills --skill pdfkit
$git clone --depth 1 https://github.com/TalissonVitorino/kmp-ios-skills.git /tmp/kmp-ios-skills && mkdir -p ~/.claude/skills && cp -r /tmp/kmp-ios-skills/ios/pdfkit ~/.claude/skills/pdfkit
Installe pour moi cette Agent Skill : https://github.com/TalissonVitorino/kmp-ios-skills/tree/96a970b75c86324b09fdb6b2cbadab0a147fd6c1/ios/pdfkit — lis d’abord son SKILL.md et ses scripts, et ne l’installe dans mon dossier de compétences qu’après avoir vérifié qu’elle est sûre.

Résumé

Description d’origine · MITDisplay, render, annotate, search, and fill PDFs on iOS with Apple's PDFKit. Covers wrapping PDFView in SwiftUI (UIViewRepresentable), PDFDocument (init(url:)/init(data:), page(at:), write(to:), encryption/permissions, unlock), PDFPage (bounds(for:), thumbnail(of:for:), draw(with:to:)), PDFAnnotation (highlight/freeText/ink/widget via init(bounds:forType:withProperties:), subtype), PDFSelection text extraction + findString search, PDFThumbnailView, AcroForm form filling via widget annotations + fieldName, PDFOutline, and PDFDocumentDelegate. Use when showing statements/receipts/contracts, generating or exporting a PDF, highlighting or marking up pages, or filling a form. For the SwiftUI↔UIKit bridge see swiftui-uikit-interop; for encrypting exported files at rest / password handling see swift-security; for OCR of scanned/image PDFs see vision-framework; for locale-aware amounts rendered into a PDF see swift-formatstyle.
Le SKILL.md ci-dessous est reproduit depuis TalissonVitorino/kmp-ios-skills (commit 96a970b) sous licence MIT. Le texte est inchangé ; seules les métadonnées d’en-tête du fichier sont omises, les images sont affichées sous forme de liens et les fichiers très longs sont tronqués. Copyright 2026 Talisson Vitorino. Licence : LICENSE. Seul le fichier d’instructions est affiché ; consultez le dépôt d’origine pour les éventuels scripts.

PDFKit (iOS)

Render, navigate, annotate, search, and fill PDFs. import PDFKit. iOS 11+; this skill targets the iOS 26 era. PDFKit is UIKit-based — there is no native SwiftUI PDFView, so wrap it with UIViewRepresentable (see swiftui-uikit-interop).

  • Threading: PDFView and all UI live on the main thread. Loading a large PDFDocument, rendering thumbnails, and write(to:) are expensive — run them off the main actor and hand the finished object back to the view.
  • Fintech note: never write account statements/receipts to a world-readable path. Export to an app-sandbox URL and, if it leaves the device or persists, encrypt at rest — see swift-security. PDFKit's own owner/user passwords (below) are AcroForm encryption, not a substitute for file-level protection.

Contents

<a id="display"></a>

Display in SwiftUI

PDFView is a UIView. Bridge it once and drive it through the document.

import SwiftUI
import PDFKit

struct PDFKitView: UIViewRepresentable {
    let document: PDFDocument

    func makeUIView(context: Context) -> PDFView {
        let view = PDFView()
        view.autoScales = true                    // fit-to-width, tracks rotation/resize
        view.displayMode = .singlePageContinuous   // .singlePage | .twoUp | .twoUpContinuous
        view.displayDirection = .vertical          // or .horizontal
        view.usePageViewController(false)          // true = page-curl (iBooks-style)
        return view
    }

    func updateUIView(_ view: PDFView, context: Context) {
        if view.document !== document { view.document = document }
    }
}
  • Load off-main, then assign on main:
func loadDocument(at url: URL) async -> PDFDocument? {
    await Task.detached(priority: .userInitiated) { PDFDocument(url: url) }.value
}
  • Key PDFView knobs: autoScales, scaleFactor / minScaleFactor / maxScaleFactor, scaleFactorForSizeToFit, pageBreakMargins, backgroundColor, pageShadowsEnabled.
  • PDFView.document is optional; setting it re-lays-out. currentPage, go(to:), goToNextPage(_:) / goToPreviousPage(_:) for programmatic navigation.
  • Observe .PDFViewPageChanged, .PDFViewScaleChanged, .PDFViewSelectionChanged (post from NotificationCenter) to reflect state in SwiftUI.

<a id="document"></a>

PDFDocument — load, save, encrypt

let doc = PDFDocument(url: fileURL)        // returns nil if unreadable/corrupt
let doc2 = PDFDocument(data: pdfData)      // from a network/blob payload

let count = doc?.pageCount ?? 0
let page  = doc?.page(at: 0)               // 0-based; nil out of range
let index = page.map { doc?.index(for: $0) }
doc?.insert(newPage, at: count)            // also removePage(at:), exchangePage(at:withPageAt:)
  • Save: write(to:) / write(to:withOptions:) return Bool; dataRepresentation() returns Data. Both flatten in-memory edits (added pages, annotations) into the output.
let ok = doc.write(to: outURL)             // Bool — check it
let data = doc.dataRepresentation()        // for upload / Keychain-adjacent storage
  • Encryption / permissions — supply passwords as write options (AcroForm-level):
let opts: [PDFDocumentWriteOption: Any] = [
    .userPasswordOption: userPassword,      // required to open
    .ownerPasswordOption: ownerPassword,    // required to change permissions
]
doc.write(to: outURL, withOptions: opts)
  • Reading a locked doc: isEncrypted / isLocked are true until you call unlock(withPassword:) (returns Bool). allowsCopying, allowsPrinting, allowsCommenting, allowsFormFieldEntry report the permission flags.
  • Metadata: documentAttributes ([AnyHashable: Any]) keyed by PDFDocumentAttribute (.titleAttribute, .authorAttribute, .creationDateAttribute, …).
  • Do not hardcode passwords; source them from the user or Keychain (swift-security).

<a id="page"></a>

PDFPage — bounds, thumbnail, render

A PDFPage exposes geometry, a bitmap, and raw drawing. PDFDisplayBox selects the box: .mediaBox (full sheet), .cropBox (visible, PDFKit's default), .bleedBox, .trimBox, .artBox.

let bounds = page.bounds(for: .cropBox)     // CGRect in PDF (Core Graphics) space
let rotation = page.rotation                 // 0/90/180/270
let text = page.string                       // full page text, or nil
let n = page.numberOfCharacters
  • Thumbnail (returns a UIImage, cheap for list cells):
let thumb = page.thumbnail(of: CGSize(width: 120, height: 160), for: .cropBox)
  • Custom render into your own context (export, share sheet, watermark):
let box = PDFDisplayBox.cropBox
let pageRect = page.bounds(for: box)
let renderer = UIGraphicsImageRenderer(size: pageRect.size)
let image = renderer.image { ctx in
    UIColor.white.set(); ctx.fill(pageRect)
    let cg = ctx.cgContext
    cg.translateBy(x: 0, y: pageRect.height)   // flip: PDF origin is bottom-left
    cg.scaleBy(x: 1, y: -1)
    page.draw(with: box, to: cg)               // renders page content + annotations
}
  • PDF coordinate space is bottom-left origin; UIKit is top-left. Flip the CTM (as above) whenever you draw a page into a UIKit/CGContext target, and when converting view points use page.convert(_:to:) / PDFView.convert(_:to:).

<a id="navsearch"></a>

Navigate, select, search

Text extraction via PDFSelection:

let whole = page.string                                  // per page
let range = page.selection(for: NSRange(location: 0, length: 20))  // chars → selection
let sel = doc.selection(from: startPos, to: endPos)      // across pages (PDFDestination)
let picked = sel?.string                                 // extracted text

Search — synchronous returns [PDFSelection]; options are NSString.CompareOptions (.caseInsensitive, .backwards, .literal). PDFKit does not honor .regularExpression.

let hits = doc.findString("overdue", withOptions: [.caseInsensitive])
if let first = hits.first {
    first.color = .yellow
    pdfView.setCurrentSelection(first, animate: true)
    pdfView.go(to: first)                                // scroll into view
}
pdfView.highlightedSelections = hits                     // persistent highlight overlay
  • Incremental search: findString(_:fromSelection:withOptions:) (one next hit), or the async beginFindString(_:withOptions:) which posts .PDFDocumentDidBeginFind / .PDFDocumentDidFindMatch / .PDFDocumentDidEndFind — use it for large docs so the UI never blocks.
  • PDFSelection: .pages, .string, .attributedString, .bounds(for:), .selectionsByLine() (split multi-line selections into per-line rects — needed to lay down accurate highlight annotations). Combine with .add(_:) / extend(...).

<a id="annotations"></a>

Annotations

Create with the modern initializer init(bounds:forType:withProperties:) — bounds is in page coordinates, forType is a PDFAnnotationSubtype. Then page.addAnnotation(_:).

// Free-text note
let note = PDFAnnotation(bounds: CGRect(x: 40, y: 700, width: 200, height: 24),
                         forType: .freeText, withProperties: nil)
note.contents = "Reviewed 2026-08-03"
note.font = .systemFont(ofSize: 12)
note.fontColor = .label
note.color = .clear                              // background fill
page.addAnnotation(note)
// Highlight the current search/text selection (one annotation per visual line)
for lineSel in selection.selectionsByLine() {
    guard let p = lineSel.pages.first else { continue }
    let h = PDFAnnotation(bounds: lineSel.bounds(for: p),
                          forType: .highlight, withProperties: nil)
    h.color = .systemYellow                       // .markupType is .highlight by subtype
    p.addAnnotation(h)
}
// Ink (freehand) — attach one or more UIBezierPaths in page space
let ink = PDFAnnotation(bounds: page.bounds(for: .cropBox),
                        forType: .ink, withProperties: nil)
ink.color = .systemBlue
ink.add(bezierPath)                               // repeat for multiple strokes; .paths reads them back
page.addAnnotation(ink)
  • Subtypes: .highlight, .underline, .strikeOut, .freeText, .ink, .square, .circle, .line, .stamp, .text (note icon), .link, .widget (forms, below).
  • Read annotation.type (raw subtype string) and .bounds; enumerate page.annotations.
  • Remove with page.removeAnnotation(_:). Edits are in-memory until you write(to:) / dataRepresentation().
  • Deep dive (markup colors, PDFBorder, stamps, links, PDFAnnotationKey properties) in references/annotations-forms.md.

<a id="forms"></a>

Forms (AcroForm widgets)

Form fields are .widget annotations. Locate them by fieldName, set the value, and save. Never guess field names — enumerate them first.

func setField(_ name: String, to value: String, in doc: PDFDocument) {
    for i in 0..<doc.pageCount {
        guard let page = doc.page(at: i) else { continue }
        for a in page.annotations where a.fieldName == name {
            switch a.widgetFieldType {
            case .text:
                a.widgetStringValue = value
            case .button:
                // checkbox / radio: match the field's on-state string
                a.buttonWidgetState = (value == a.buttonWidgetStateString) ? .onState : .offState
            case .choice:
                a.widgetStringValue = value          // list/combo selection
            default:
                break
            }
        }
    }
}
  • Field metadata: widgetFieldType (.text, .button, .choice, .signature), widgetControlType (.pushButtonControl, .radioButtonControl, .checkBoxControl), fieldName, isReadOnly, maximumLength, hasComb; choice options via the .widgetOptions annotation key.
  • Text value ↔ widgetStringValue; checkbox/radio state ↔ buttonWidgetState (.onState / .offState), whose "on" name is buttonWidgetStateString.
  • Flatten before sharing if the recipient shouldn't edit fields: render each page with page.draw(with:to:) into a fresh UIGraphicsPDFRenderer context (widgets become static pixels). Full flattening recipe in references/annotations-forms.md.
  • Respect allowsFormFieldEntry; a locked/encrypted doc may reject edits until unlocked.

<a id="thumbnails-outline"></a>

Thumbnails & outline

PDFThumbnailView — a ready-made page navigator; bind it to the same PDFView.

let thumbs = PDFThumbnailView()
thumbs.pdfView = pdfView                 // shares selection/navigation with the main view
thumbs.thumbnailSize = CGSize(width: 80, height: 100)
thumbs.layoutMode = .vertical            // or .horizontal

PDFOutline — the document's table of contents (bookmarks):

if let root = doc.outlineRoot {
    for i in 0..<root.numberOfChildren {
        let item = root.child(at: i)!
        let title = item.label                 // section title
        if let dest = item.destination {       // PDFDestination: page + point
            // dest.page, dest.point — go(to:) it on tap
        }
    }
}
  • Outline is a tree — recurse via numberOfChildren / child(at:). doc.outlineItem(for:) maps a selection back to its outline node.

<a id="delegate"></a>

PDFDocumentDelegate

Set doc.delegate to customize page behavior or observe unlock/find events.

  • classForPage() — return a PDFPage subclass so every page uses your custom draw(with:to:) (e.g. stamp a "COPY" / account-number watermark on render without mutating the file):
final class WatermarkPage: PDFPage {
    override func draw(with box: PDFDisplayBox, to context: CGContext) {
        super.draw(with: box, to: context)           // draw the real page first
        context.saveGState()
        // …draw watermark text into `context` (page space, bottom-left origin)…
        context.restoreGState()
    }
}

final class DocDelegate: NSObject, PDFDocumentDelegate {
    func classForPage() -> AnyClass { WatermarkPage.self }
    func documentDidUnlock(_ notification: Notification) { /* re-enable UI */ }
}
  • Also: classForAnnotationType(_:) to substitute a custom annotation class, and the find-delegate callbacks (didMatchString(_:)) for async search results.

<a id="checklist"></a>

Correctness checklist

  • PDFView created/mutated only on the main thread; PDFDocument(url:), thumbnails, and write(to:) run off-main, result handed back on main.
  • SwiftUI integration goes through UIViewRepresentable (no native SwiftUI PDFView); updateUIView swaps document only when it actually changed (!==).
  • Return values checked: PDFDocument(url:) and page(at:) are optional; write(to:) and unlock(withPassword:) return Bool.
  • Page drawing into a CGContext flips the CTM (PDF is bottom-left origin); point conversions use convert(_:to:), not manual math.
  • Correct PDFDisplayBox chosen (.cropBox for what the user sees, .mediaBox for the full sheet) consistently across bounds/thumbnail/draw.
  • Annotation bounds are in page coordinates; highlights use selectionsByLine() rects; annotations added with addAnnotation and persisted via write(to:)/dataRepresentation().
  • Form fields located by fieldName (enumerated, not guessed); text→widgetStringValue, button→buttonWidgetState vs buttonWidgetStateString; flatten before sharing read-only.
  • Search treats findString as synchronous/blocking on large docs — use beginFindString + notifications instead; .regularExpression is unsupported.
  • Exported financial PDFs written to the app sandbox and protected at rest (swift-security); passwords never hardcoded.
Voir le texte intégral de la licence (MIT)
MIT License

Copyright (c) 2026 Talisson Vitorino

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Voir le NOTICE
# NOTICE

`kmp-ios-skills` is distributed under the [MIT License](LICENSE). It bundles skills adapted from several upstream projects, all under permissive licenses. Attribution follows, per skill.

## Apache License 2.0

Full license text: [`licenses/APACHE-2.0.txt`](licenses/APACHE-2.0.txt).

### [android/skills](https://github.com/android/skills) — Copyright Google LLC

Copied and, where noted in the skill body, adapted:

| Skill | Path |
|---|---|
| `agp-9-upgrade` | `android/agp-9-upgrade` |
| `android-cli` | `android/android-cli` |
| `android-intent-security` | `android/android-intent-security` |
| `android-profiler` | `android/android-profiler` |
| `camerax` | `android/camerax` |
| `compose-adaptive` | `android/compose-adaptive` |
| `compose-theming-styles` | `android/compose-theming-styles` |
| `edge-to-edge` | `android/edge-to-edge` |
| `perfetto-sql` | `android/perfetto-sql` |
| `perfetto-trace-analysis` | `android/perfetto-trace-analysis` |
| `play-billing-upgrade` | `android/play-billing-upgrade` |
| `play-policy-insights` | `android/play-policy-insights` |
| `restore-credentials` | `android/restore-credentials` |
| `verified-email` | `android/verified-email` |
| `r8-analyzer` | `android/r8-analyzer` |

The Navigation 3 section and the recipe tree under `cross-platform/navigation/references/` also derive from `android/skills`. That skill is a merge of three originals (Jetpack Navigation Compose, Navigation 3, and multiplatform navigation); only the Navigation 3 material is Google's.

Modified: two skills were renamed to avoid ambiguous identifiers inside a mixed library — the frontmatter `name` of `compose-theming-styles` was `styles`, and `play-billing-upgrade` was `play-billing-library-version-upgrade`. Content is otherwise unchanged.

Portions of the reference files reproduce documentation from developer.android.com, also under Apache 2.0 / CC BY 2.5 as published by Google.

### [getsentry/sentry-skills](https://github.com/getsentry/sentry-skills) — Copyright Functional Software, Inc. (Sentry)

| Skill | Path |
|---|---|
| `sentry-fix-issues` | `workflow/sentry-fix-issues` |

Modified: the parent-skill breadcrumb link and the `disable-model-invocation` flag were removed so the skill stands alone.

## MIT License

### [ahmed3elshaer/everything-claude-code-mobile](https://github.com/ahmed3elshaer/everything-claude-code-mobile)

The cross-platform and Android pattern skills derive from this project — among them `accessibility-patterns`, `analytics-patterns`, `android-patterns`, `app-lifecycle`, `ci-cd-patterns`, `combine-framework`, `core-data`, `coroutines-patterns`, `deep-linking`, `expect-actual`, `feature-builder`, `feature-flags`, `gradle-patterns`, `image-loading`, `jetpack-compose`, `kmp-build-setup`, `kmp-di`, `kmp-networking`, `kmp-repositories`, `koin-patterns`, `ktor-patterns`, `liquid-glass`, `localization-patterns`, `m3-expressive`, `mobile-checkpoint`, `mobile-security`, `mobile-testing`, `multiplatform-settings`, `mvi-architecture`, `offline-first`, `pagination-patterns`, `push-notifications`, `room-patterns`, `shared-coroutines`, `shared-models`, `sqldelight-patterns`, `swift-patterns`, `swiftui-patterns`.

Modified here: dependency versions updated and verified, dead APIs replaced (e.g. Firebase Dynamic Links, deprecated `EncryptedSharedPreferences` guidance), compile-blocking samples fixed, and descriptions rewritten to disambiguate overlapping skills. `feature-builder` was rewritten to drop an orchestration pipeline that referenced sub-agents and MCP servers not present here.

### [avdlee/swiftui-agent-skill](https://github.com/avdlee/swiftui-agent-skill) — Antoine van der Lee

| Skill | Path |
|---|---|
| `swiftui-expert-skill` | `ios/swiftui-expert-skill` |

### [affaan-m/everything-claude-code](https://github.com/affaan-m/everything-claude-code)

| Skill | Path |
|---|---|
| `ios-icon-gen` | `ios/ios-icon-gen` |
| `swift-concurrency-6-2` | `ios/swift-concurrency-6-2` |
| `swift-protocol-di-testing` | `ios/swift-protocol-di-testing` |

## Original work

Written from scratch for this library, grounded in the official Apple, Kotlin and Android documentation, then verified by an independent adversarial pass that checked every API symbol against those docs:

`activitykit`, `app-clips`, `app-intents`, `app-store-review`, `apple-on-device-ai`, `authentication`, `background-processing`, `callkit`, `cloudkit`, `contacts-framework`, `core-nfc`, `coreml`, `debugging-instruments`, `device-integrity`, `financekit`, `ios-simulator`, `mapkit`, `metrickit`, `natural-language`, `passkit`, `pdfkit`, `photokit`, `storekit`, `swift-api-design-guidelines`, `swift-architecture`, `swift-charts`, `swift-formatstyle`, `swift-security`, `swiftlint`, `swiftui-uikit-interop`, `swiftui-webkit`, `tipkit`, `vision-framework`, `widgetkit`, plus `kmp-money`, `kmp-tls-pinning`, `android-device-integrity`, `mobile-session-security`, `kmp-ios-integration`, `kmp-logging`, `compose-resources`, `error-handling-result`, `swift-concurrency`, `swiftui-observation`, `swift-package-manager`, `swiftdata`, `prepare-merge-request`.

Trademarks — Apple, Swift, SwiftUI, Xcode, Android, Kotlin, Gradle, Firebase and Sentry — belong to their respective owners. This project is not affiliated with, endorsed by, or sponsored by any of them.