@tobyt/expo-pdf-markup 0.0.0-next.20261121170125

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/LICENSE +21 -0
  3. package/README.md +238 -0
  4. package/android/.editorconfig +2 -0
  5. package/android/build.gradle +33 -0
  6. package/android/src/main/AndroidManifest.xml +2 -0
  7. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationGeometry.kt +85 -0
  8. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationHitTester.kt +76 -0
  9. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationModel.kt +41 -0
  10. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationRenderer.kt +254 -0
  11. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationSerializer.kt +239 -0
  12. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationsChangeEmitter.kt +31 -0
  13. package/android/src/main/java/dev/terhoeven/expopdfmarkup/BookPager.kt +66 -0
  14. package/android/src/main/java/dev/terhoeven/expopdfmarkup/BookTurnPolicy.kt +117 -0
  15. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ContinuousPdfView.kt +1107 -0
  16. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupModule.kt +116 -0
  17. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupView.kt +317 -0
  18. package/android/src/main/java/dev/terhoeven/expopdfmarkup/TouchInterceptPolicy.kt +20 -0
  19. package/build/ExpoPdfMarkup.types.d.ts +193 -0
  20. package/build/ExpoPdfMarkup.types.d.ts.map +1 -0
  21. package/build/ExpoPdfMarkup.types.js +2 -0
  22. package/build/ExpoPdfMarkup.types.js.map +1 -0
  23. package/build/ExpoPdfMarkupModule.d.ts +2 -0
  24. package/build/ExpoPdfMarkupModule.d.ts.map +1 -0
  25. package/build/ExpoPdfMarkupModule.js +4 -0
  26. package/build/ExpoPdfMarkupModule.js.map +1 -0
  27. package/build/ExpoPdfMarkupModule.web.d.ts +2 -0
  28. package/build/ExpoPdfMarkupModule.web.d.ts.map +1 -0
  29. package/build/ExpoPdfMarkupModule.web.js +4 -0
  30. package/build/ExpoPdfMarkupModule.web.js.map +1 -0
  31. package/build/ExpoPdfMarkupView.d.ts +4 -0
  32. package/build/ExpoPdfMarkupView.d.ts.map +1 -0
  33. package/build/ExpoPdfMarkupView.js +20 -0
  34. package/build/ExpoPdfMarkupView.js.map +1 -0
  35. package/build/ExpoPdfMarkupView.web.d.ts +8 -0
  36. package/build/ExpoPdfMarkupView.web.d.ts.map +1 -0
  37. package/build/ExpoPdfMarkupView.web.js +953 -0
  38. package/build/ExpoPdfMarkupView.web.js.map +1 -0
  39. package/build/index.d.ts +5 -0
  40. package/build/index.d.ts.map +1 -0
  41. package/build/index.js +5 -0
  42. package/build/index.js.map +1 -0
  43. package/build/parseAnnotations.d.ts +11 -0
  44. package/build/parseAnnotations.d.ts.map +1 -0
  45. package/build/parseAnnotations.js +49 -0
  46. package/build/parseAnnotations.js.map +1 -0
  47. package/build/pdfjs.d.ts +3 -0
  48. package/build/pdfjs.d.ts.map +1 -0
  49. package/build/pdfjs.js +8 -0
  50. package/build/pdfjs.js.map +1 -0
  51. package/build/pdfjs.web.d.ts +2 -0
  52. package/build/pdfjs.web.d.ts.map +1 -0
  53. package/build/pdfjs.web.js +2 -0
  54. package/build/pdfjs.web.js.map +1 -0
  55. package/build/web/annotationUtils.d.ts +54 -0
  56. package/build/web/annotationUtils.d.ts.map +1 -0
  57. package/build/web/annotationUtils.js +363 -0
  58. package/build/web/annotationUtils.js.map +1 -0
  59. package/build/web/bookMode.d.ts +77 -0
  60. package/build/web/bookMode.d.ts.map +1 -0
  61. package/build/web/bookMode.js +169 -0
  62. package/build/web/bookMode.js.map +1 -0
  63. package/build/web/layout.d.ts +8 -0
  64. package/build/web/layout.d.ts.map +1 -0
  65. package/build/web/layout.js +22 -0
  66. package/build/web/layout.js.map +1 -0
  67. package/build/web/types.d.ts +15 -0
  68. package/build/web/types.d.ts.map +1 -0
  69. package/build/web/types.js +2 -0
  70. package/build/web/types.js.map +1 -0
  71. package/expo-module.config.json +9 -0
  72. package/fixtures/annotations-v1-array.json +124 -0
  73. package/fixtures/annotations-v1.json +130 -0
  74. package/fixtures/ink-cleanup-expected-array.json +95 -0
  75. package/fixtures/ink-cleanup-expected-object.json +95 -0
  76. package/fixtures/ink-cleanup-input.json +99 -0
  77. package/ios/AnnotationModels.swift +417 -0
  78. package/ios/AnnotationSerializer.swift +407 -0
  79. package/ios/ExpoPdfMarkup.podspec +28 -0
  80. package/ios/ExpoPdfMarkupModule.swift +70 -0
  81. package/ios/ExpoPdfMarkupView+Book.swift +455 -0
  82. package/ios/ExpoPdfMarkupView+Ink.swift +168 -0
  83. package/ios/ExpoPdfMarkupView+Markup.swift +151 -0
  84. package/ios/ExpoPdfMarkupView+Move.swift +277 -0
  85. package/ios/ExpoPdfMarkupView.swift +385 -0
  86. package/ios/StampPDFAnnotation.swift +118 -0
  87. package/ios/Tests/AnnotationCoordinateTests.swift +424 -0
  88. package/ios/Tests/AnnotationModelTests.swift +178 -0
  89. package/ios/Tests/AnnotationSerializerTests.swift +486 -0
  90. package/ios/Tests/AreaMarkupTests.swift +279 -0
  91. package/ios/Tests/BookModeTests.swift +538 -0
  92. package/ios/Tests/ExpoPdfMarkupViewTests.swift +318 -0
  93. package/ios/Tests/RotatedAnnotationRenderingTests.swift +411 -0
  94. package/ios/Tests/StampPDFAnnotationTests.swift +128 -0
  95. package/ios/Tests/book-sample.pdf +207 -0
  96. package/ios/Tests/single-page.pdf +52 -0
  97. package/ios/Tests/test.pdf +0 -0
  98. package/metro.d.ts +5 -0
  99. package/metro.js +133 -0
  100. package/package.json +95 -0
  101. package/src/ExpoPdfMarkup.types.ts +185 -0
  102. package/src/ExpoPdfMarkupModule.ts +2 -0
  103. package/src/ExpoPdfMarkupModule.web.ts +2 -0
  104. package/src/ExpoPdfMarkupView.tsx +43 -0
  105. package/src/ExpoPdfMarkupView.web.tsx +1197 -0
  106. package/src/index.ts +4 -0
  107. package/src/parseAnnotations.ts +52 -0
  108. package/src/pdfjs.ts +8 -0
  109. package/src/pdfjs.web.ts +1 -0
  110. package/src/web/annotationUtils.ts +452 -0
  111. package/src/web/bookMode.ts +186 -0
  112. package/src/web/layout.ts +30 -0
  113. package/src/web/types.ts +15 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,176 @@
1
+ # @tobyt/expo-pdf-markup
2
+
3
+ ## 2.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 08d6547: Fix iOS annotation placement, moving and erasing on cropped or rotated PDFs, including stamps in thumbnails and text after reopening.
8
+
9
+ iOS annotation coordinates and `onTextInputRequested.point` now use the visible page, with `(0, 0)` at its bottom-left after rotation. Some annotations saved by older iOS versions may move; existing data is not automatically migrated. Back up saved annotations before upgrading.
10
+
11
+ Rebuild your native iOS app to apply these fixes.
12
+
13
+ - c9f8824: On iOS, drag a rectangle to highlight or underline any page, including scans. This replaces text-selection highlighting and underlining; marks no longer snap to text lines.
14
+
15
+ Switch `annotationMode` to `"none"` to scroll, zoom or turn pages by touch. Programmatic page changes and book-mode keyboard controls still work while marking.
16
+
17
+ Rebuild your native iOS app to use this behaviour.
18
+
19
+ ## 1.2.0
20
+
21
+ ### Minor Changes
22
+
23
+ - 055cf02: Add book mode. `ExpoPdfMarkupView` takes a new `displayMode` prop, `'continuous'` (the default) or `'book'`. Book mode shows one page at a time, fitted to the view, and turns pages sideways with a slide animation: swipe horizontally, tap the outer quarter of the view on either side, or press the arrow or Page Up / Page Down keys, which is what Bluetooth page-turner pedals send. Pinch to zoom still works, and while the page is zoomed in a swipe pans instead of turning. Markup tools keep working in book mode and take priority over swipes and taps, while hardware keys still turn the page. `page` and `onPageChanged` behave the same in both modes, and changing `displayMode` or rotating keeps the current page. Leaving `displayMode` out keeps today's continuous behaviour. The library adds no user-facing text: page indicators and announcements are up to your app. Book mode needs a new native build.
24
+
25
+ ## 1.1.4
26
+
27
+ ### Patch Changes
28
+
29
+ - 63fdb1c: Always serialise `paths` on ink annotations, even when the platform returns no stroke geometry. The `Annotation` type declares `paths` as non-optional, but iOS and Android both omitted the key when geometry was missing, so consumers dereferencing `annotation.paths` crashed with a `TypeError` instead of seeing an empty stroke list.
30
+ - 2463b24: Fix `withPdfMarkup` leaving a stale pdfjs worker in `public/` after a pdfjs-dist upgrade. The Metro plugin copied `pdf.worker.min.mjs` and the `wasm/` assets only when they were absent, so once a project had them the copies were pinned to whichever pdfjs-dist version was installed first. Upgrading pdfjs-dist then broke web rendering with `The API version "x" does not match the Worker version "y"`, and silently stale wasm assets could mis-decode JBIG2/CCITT fax, JPEG2000 and ICC colour data. The plugin now compares each file against the installed pdfjs-dist and re-copies whenever it differs, so upgrades and downgrades both self-correct while unchanged files stay a no-op on Metro restart.
31
+ - 3aeeae8: Revert the iOS 27 beta workaround for the PDFKit ink annotation regression. Ink annotations use PDFKit's built-in ink storage again now that `PDFAnnotation.add(_:)`/`.paths` behaves correctly, restoring the standard rendering and serialisation behaviour.
32
+
33
+ ## 1.1.3
34
+
35
+ ### Patch Changes
36
+
37
+ - 5bb3360: Work around an iOS 27 beta PDFKit regression where `PDFAnnotation.add(_:)`/`.paths` silently drops ink annotation stroke geometry. Ink annotations now store and render their own stroke data instead of relying on PDFKit's built-in ink storage, so drawing, persisting, erasing and moving ink markup continues to behave correctly on iOS 27.
38
+
39
+ ## 1.1.2
40
+
41
+ ### Patch Changes
42
+
43
+ - 2970fc6: Support pdfjs-dist v6 on the web renderer. Adapt to the v6 API changes: `getDocument` now takes a parameters object (`{ url }`) rather than a bare string, and `PDFDocumentProxy.destroy()` was removed in favour of `loadingTask.destroy()`. Pass `canvas: null` to `page.render()` so pdfjs keeps rendering into our own 2D context (the v6 types made `canvas` required) without taking ownership of the canvas element.
44
+
45
+ pdfjs-dist v6 also moved image decoding (JBIG2/CCITT fax, JPEG2000, ICC colour) into WebAssembly, which is fetched at runtime from a configurable `wasmUrl`. Without it, affected image data — scanned pages and some music notation — renders blank. `withPdfMarkup` now copies the WASM files to `public/wasm/`, the view sets `wasmUrl` to `./wasm/` by default, and a new `setPdfJsWasmUrl()` export lets consumers point it elsewhere.
46
+
47
+ These calls remain compatible with earlier pdfjs-dist versions, so the optional peer dependency range is unchanged.
48
+
49
+ - a361c91: Verify compatibility with Expo SDK 57 (React Native 0.86). Fix TypeScript strictness errors surfaced by the updated toolchain (`verbatimModuleSyntax`, `noUncheckedIndexedAccess`) with no behaviour change.
50
+
51
+ ## 1.1.1
52
+
53
+ ### Patch Changes
54
+
55
+ - 3f4fa8c: Android: fix touch-interception lifecycle in the PDF view. The view previously called `requestDisallowInterceptTouchEvent(true)` on every touch event and never released it, and in-progress gestures were never reset when interrupted. This could leave stale touch state on ancestor views shared with sibling screens (e.g. list rows behind the PDF screen becoming unresponsive to taps after navigating back, especially after locking/unlocking the device), and caused unnecessary gesture-handler contention while scrolling.
56
+
57
+ Now the parent intercept hold is requested on `ACTION_DOWN` and released on the final `ACTION_UP`/`ACTION_CANCEL` (held across multi-touch pinch), and all in-progress gestures (ink stroke, highlight/underline drag, annotation move, fling) are cancelled and the hold released when the window loses focus (device lock) or the view detaches. Note: an ink stroke interrupted by a device lock is discarded rather than committed.
58
+
59
+ ## 1.1.0
60
+
61
+ ### Minor Changes
62
+
63
+ - 24c58b8: Add `stamp` annotations for placing consumer-defined text glyphs (e.g. emoji) onto a PDF. New `StampAnnotation` type, `'stamp'` annotation mode, and `stampText`/`stampSize` props let apps arm a stamp (from their own picker UI) and tap to place it; stamps support move and eraser like other bounds-based annotations. A new `StampDefinition` type is exported as a convenience shape for organizing a custom stamp set. Image-backed stamps were intentionally left out — a stored local file path can go stale (app reinstall, cache eviction) and silently break previously-placed stamps, so this stays text-only for now.
64
+
65
+ ### Patch Changes
66
+
67
+ - 850b4f9: Routine dependency maintenance: upgrade to the latest Expo SDK 55 patch release. Bumps `expo` (55.0.5 → 55.0.26) and `react-native` (0.83.2 → 0.83.6) in the module, and `expo`, `expo-asset`, `expo-font`, `react-native`, `react`, `react-dom` to their SDK 55.0.26-compatible versions in the example app. No runtime behavior changes.
68
+ - 95b8c0d: Routine dependency maintenance: patch/minor bumps for transitive and dev dependencies (`@babel/plugin-transform-modules-systemjs`, `@xmldom/xmldom`, `lodash`, `node-forge`, `flatted`, `picomatch`, `yaml`, `brace-expansion`, `shell-quote`, `markdown-it`, `linkify-it`, `form-data`, `hasown`, `ws`), example app `react`/`react-dom`/`@types/react`, and CI Actions (`checkout`, `setup-node`, `upload-pages-artifact`, `deploy-pages`). No runtime behavior changes.
69
+
70
+ ## 1.0.1
71
+
72
+ ### Patch Changes
73
+
74
+ - 16e0e87: Fix iOS ink strokes missing their first contact point
75
+
76
+ Replaces `UIPanGestureRecognizer` with direct `touchesBegan/Moved/Ended` handling for ink drawing. The pan gesture had a minimum-distance threshold that silently dropped the start of every stroke — most noticeable with third-party styluses (e.g. Metapen) where initial contact is slow and deliberate.
77
+
78
+ Also disables PDFKit's built-in gesture recognizers while in ink mode, preventing text selection from firing during what was previously the gesture recognition dead zone.
79
+
80
+ ## 1.0.0
81
+
82
+ ### Major Changes
83
+
84
+ - ea50181: Stable 1.0.0 release — production-ready API for displaying and annotating PDFs on iOS, Android, and Web.
85
+
86
+ ### Patch Changes
87
+
88
+ - 906ce89: Fix Android blank PDF and scroll position loss when navigating back to a screen containing the PDF view
89
+
90
+ ## 0.6.1
91
+
92
+ ### Patch Changes
93
+
94
+ - e1a942b: Fix Android custom font rendering
95
+
96
+ ## 0.6.0
97
+
98
+ ### Minor Changes
99
+
100
+ - fc961ab: Add support for a custom font for text markups
101
+ - 26bdae1: When in Move or Eraser mode, annotations are now surrounded by an outline to indicate the scope of the move/erasure
102
+ - 26bdae1: A Move tool was added for drag and drop repositioning of annotations
103
+ - 76f9b23: Text annotations can now be edited (breaking change, see example/docs)
104
+
105
+ ### Patch Changes
106
+
107
+ - dae52fb: Reset currentSource in close
108
+ - 8146a57: Add padding to Android freeText annotation bounds to prevent text from being clipped when rendered
109
+
110
+ ## 0.5.0
111
+
112
+ ### Minor Changes
113
+
114
+ - 049130a: Example app is now deployed to Github Pages
115
+ - 049130a: Default pdfjs worker source for web implementation is now relative
116
+ - e62d562: Support optionally rendering text input prompt on JavaScript side
117
+
118
+ ## 0.4.0
119
+
120
+ ### Minor Changes
121
+
122
+ - 519e27b: Update metro config plugin so it works in a monorepo too
123
+ - 4898177: The onPageChanged event now returns page width and height.
124
+ - 5423941: When using gestures to zoom on Web, only the PDF is zoomed in/out instead of the entire UI.
125
+
126
+ ### Patch Changes
127
+
128
+ - f15901a: Move spacer in Web implementation so it only appears inbetween pages
129
+
130
+ ## 0.3.1
131
+
132
+ ### Patch Changes
133
+
134
+ - Fixed an issue on iOS, where after selecting a different colour, the previous colour would still be used for the live stroke.
135
+
136
+ ## 0.3.0
137
+
138
+ ### Minor Changes
139
+
140
+ - PDF rendering and markup is now also supported on Web.
141
+
142
+ ### Patch Changes
143
+
144
+ - 4dafaf4: Fixed documentation for the source prop - it only accepts absolute local file paths; remote URLs are not supported. Updated the README usage example to reflect real-world usage (loading a bundled asset via expo-asset) and demonstrate key props like annotationMode, annotationColor, annotationLineWidth, annotations, and the event callbacks.
145
+
146
+ ## 0.2.3
147
+
148
+ ### Patch Changes
149
+
150
+ - fix: exclude ios/Tests from podspec source_files to prevent XCTest
151
+
152
+ ## 0.2.2
153
+
154
+ ### Patch Changes
155
+
156
+ - Fix gap at top of first page on iOS by changing pageBreakMargins to apply all margin to the bottom
157
+
158
+ ## 0.2.1
159
+
160
+ ### Patch Changes
161
+
162
+ - Fix freeText annotation colour round-trip by storing the original hex string as a custom PDF annotation key, preventing loss when PDFKit's fontColor returns nil outside a document context
163
+
164
+ ## 0.2.0
165
+
166
+ ### Minor Changes
167
+
168
+ - 78be89c: Fix freeText annotation colour lost after serialisation on iOS.
169
+
170
+ PDFKit stores freeText annotation colours in `fontColor` (not `annotation.color`, which is always `.clear` for text annotations). The `toModel` serialiser was unconditionally reading `annotation.color`, causing all freeText colours to round-trip as black. The fix reads `fontColor` for `text`/`freeText` annotation types and falls back to `annotation.color` for all others.
171
+
172
+ ## 0.1.0
173
+
174
+ ### Minor Changes
175
+
176
+ - Initial release.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Toby Terhoeven
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,238 @@
1
+ # @tobyt/expo-pdf-markup
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@tobyt/expo-pdf-markup.svg)](https://www.npmjs.com/package/@tobyt/expo-pdf-markup)
4
+ [![npm downloads](https://img.shields.io/npm/dw/@tobyt/expo-pdf-markup.svg)](https://www.npmjs.com/package/@tobyt/expo-pdf-markup)
5
+ [![license](https://img.shields.io/npm/l/@tobyt/expo-pdf-markup.svg)](https://github.com/tobyt42/expo-pdf-markup/blob/main/LICENSE)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-strict-blue.svg)](https://www.typescriptlang.org/)
7
+
8
+ An Expo module for displaying and annotating PDFs, with support for iOS, Android, and Web.
9
+
10
+ **[📖 API Reference](https://tobyt42.github.io/expo-pdf-markup/api/)** · **[🚀 Example App](https://tobyt42.github.io/expo-pdf-markup/example/)**
11
+
12
+ ## Platform support
13
+
14
+ | Platform | PDF rendering | Annotations |
15
+ | -------- | ------------- | ----------- |
16
+ | iOS | ✅ | ✅ |
17
+ | Android | ✅ | ✅ |
18
+ | Web | ✅ | ✅ |
19
+
20
+ ## Installation
21
+
22
+ ```sh
23
+ npm install @tobyt/expo-pdf-markup
24
+ ```
25
+
26
+ ### iOS
27
+
28
+ ```sh
29
+ npx pod-install
30
+ ```
31
+
32
+ ### Web
33
+
34
+ Web rendering uses [pdfjs-dist](https://github.com/mozilla/pdfjs-dist). Install it as a dependency:
35
+
36
+ ```sh
37
+ npm install pdfjs-dist
38
+ ```
39
+
40
+ Then add the Metro config plugin to your `metro.config.js`:
41
+
42
+ ```js
43
+ const { getDefaultConfig } = require('expo/metro-config');
44
+ const { withPdfMarkup } = require('@tobyt/expo-pdf-markup/metro');
45
+
46
+ const config = getDefaultConfig(__dirname);
47
+ module.exports = withPdfMarkup(config);
48
+ ```
49
+
50
+ `withPdfMarkup` does three things automatically:
51
+
52
+ 1. **Patches `import.meta`** in pdfjs-dist so Metro can bundle it (pdfjs-dist uses ESM syntax in a Node.js-only code path that is otherwise unreachable in a browser).
53
+ 2. **Copies the pdfjs worker** to `public/pdf.worker.min.mjs` in your project root so it is served alongside your app (same-origin, no CORS issues). The default worker URL is `./pdf.worker.min.mjs` (relative to the page), so it works whether your app is hosted at the root or a sub-path.
54
+ 3. **Copies the pdfjs WebAssembly files** to `public/wasm/` in your project root. pdfjs-dist v6 decodes some image data (JBIG2/CCITT fax, JPEG2000, ICC colour) in WebAssembly and fetches these files at runtime; without them such content — scanned pages, some music notation — renders blank. The default WASM URL is `./wasm/` (relative to the page).
55
+
56
+ Both are regenerated on each Metro start if missing, so you can add them to `.gitignore`:
57
+
58
+ ```
59
+ public/pdf.worker.min.mjs
60
+ public/wasm/
61
+ ```
62
+
63
+ #### Using a different worker or WASM URL
64
+
65
+ If you are not using Metro (e.g. Webpack or a custom CDN), set the URLs before mounting the view:
66
+
67
+ ```ts
68
+ import { setPdfJsWorkerSrc, setPdfJsWasmUrl } from '@tobyt/expo-pdf-markup';
69
+
70
+ setPdfJsWorkerSrc('https://your-cdn.example.com/pdf.worker.min.mjs');
71
+ setPdfJsWasmUrl('https://your-cdn.example.com/wasm/');
72
+ ```
73
+
74
+ #### Asset loading on web
75
+
76
+ `expo-asset` returns a full URL on web (`https://…` or `http://…`), not a local path. Pass it directly to `source` — pdfjs accepts URLs:
77
+
78
+ ```ts
79
+ // asset.localUri on web is already a URL; the .replace() is a no-op
80
+ setPdfPath(asset.localUri.replace('file://', ''));
81
+ ```
82
+
83
+ ## Usage
84
+
85
+ Full API reference is available at **[tobyt42.github.io/expo-pdf-markup](https://tobyt42.github.io/expo-pdf-markup/api/types/ExpoPdfMarkupViewProps.html)**.
86
+
87
+ ```tsx
88
+ import { ExpoPdfMarkupView } from '@tobyt/expo-pdf-markup';
89
+ import type { AnnotationMode } from '@tobyt/expo-pdf-markup';
90
+ import { Asset } from 'expo-asset';
91
+ import { useEffect, useState } from 'react';
92
+ import { StyleSheet } from 'react-native';
93
+
94
+ export default function App() {
95
+ const [pdfPath, setPdfPath] = useState<string | null>(null);
96
+ const [annotations, setAnnotations] = useState(JSON.stringify({ version: 1, annotations: [] }));
97
+
98
+ useEffect(() => {
99
+ async function preparePdf() {
100
+ const asset = Asset.fromModule(require('./assets/document.pdf'));
101
+ await asset.downloadAsync();
102
+ if (asset.localUri) setPdfPath(asset.localUri.replace('file://', ''));
103
+ }
104
+ preparePdf();
105
+ }, []);
106
+
107
+ if (!pdfPath) return null;
108
+
109
+ return (
110
+ <ExpoPdfMarkupView
111
+ source={pdfPath}
112
+ style={StyleSheet.absoluteFill}
113
+ annotationMode="ink"
114
+ annotationColor="#FF0000"
115
+ annotationLineWidth={3}
116
+ annotations={annotations}
117
+ onLoadComplete={({ nativeEvent: { pageCount } }) => console.log(`Loaded ${pageCount} pages`)}
118
+ onPageChanged={({ nativeEvent: { page, pageCount, pageWidth, pageHeight } }) =>
119
+ console.log(`Page ${page + 1} of ${pageCount} (${pageWidth}×${pageHeight}pt)`)
120
+ }
121
+ onAnnotationsChanged={({ nativeEvent }) => setAnnotations(nativeEvent.annotations)}
122
+ onError={({ nativeEvent: { message } }) => console.error(message)}
123
+ />
124
+ );
125
+ }
126
+ ```
127
+
128
+ ### Custom text input UI
129
+
130
+ If you provide `onTextInputRequested`, the built-in native prompt is skipped and your callback is
131
+ used instead. The callback receives a request object with `mode`, `page`, `point`, and
132
+ `currentText` for edit flows, so you can prefill your own UI when the user taps an existing text
133
+ annotation while the text tool is active.
134
+
135
+ ## Development
136
+
137
+ This module uses the [Expo Modules API](https://docs.expo.dev/modules/overview/). The `example` directory contains a test app.
138
+
139
+ The library development environment and example use Expo SDK 58, React 19.3, and React Native
140
+ 0.88. Use Node.js 22.13+ or 24.3+ (even-numbered releases). Install dependencies with `npm ci`
141
+ in both the root and `example` directories.
142
+
143
+ Builds and type checks use TypeScript directly. ESLint uses the public Expo flat config,
144
+ and Jest uses `jest-expo` presets for iOS, Android, Web, and Node. Test types are checked
145
+ separately with `npm run typecheck:tests`, since Jest uses Babel to transform TypeScript.
146
+ React and React DOM are pinned together for the web tests.
147
+
148
+ `expo-doctor` in `example` reports duplicate copies of native dependencies from the separate
149
+ root and example installs, including the library's peer dependencies. Their versions match;
150
+ the native builds select the example's copies. Keep both installations aligned when upgrading.
151
+
152
+ ```sh
153
+ # Build the module
154
+ npm run build
155
+
156
+ # Run the example app
157
+ cd example
158
+ npx expo start
159
+ ```
160
+
161
+ ## Core Team
162
+
163
+ <table>
164
+ <tr>
165
+ <td align="center"><a href="https://github.com/tobyt42"><img src="https://avatars.githubusercontent.com/u/1678364?v=4" width="100px;" alt=""/><br /><sub><b>Toby Terhoeven</b></sub></a><br /></td>
166
+ </tr>
167
+ </table>
168
+
169
+ ## Used by
170
+
171
+ - [Choir](https://www.thechoirapp.com) — a choir practice app for iOS, Android and Web
172
+
173
+ ## License
174
+
175
+ MIT
176
+
177
+ ### Annotation coordinates and compatibility
178
+
179
+ Annotations use zero-origin visible-page coordinates, in PDF points with y increasing upward.
180
+ See [the coordinate contract and upgrade guidance](docs/annotation-coordinates.md) for cropped
181
+ and rotated pages, v1 compatibility limits, and native rebuild requirements.
182
+
183
+ ### Reading annotation JSON
184
+
185
+ Ink points in an annotation set may be stored in object form (`{"x": 40, "y": 100}`) or array
186
+ form (`[40, 100]`), and one ink stroke may mix both. Use `parseAnnotations` to read raw
187
+ annotation JSON in your own code: it accepts either form and always returns ink points as
188
+ `{ x, y }` objects, so the `AnnotationPoint` and `InkAnnotation` types are unchanged.
189
+
190
+ ```tsx
191
+ import { parseAnnotations, type InkAnnotation } from '@tobyt/expo-pdf-markup';
192
+
193
+ const { annotations } = parseAnnotations(storedJson);
194
+ const inks = annotations.filter((a): a is InkAnnotation => a.type === 'ink');
195
+ ```
196
+
197
+ Malformed ink points are skipped. `parseAnnotations` throws if the JSON can't be parsed or has
198
+ no `annotations` array, so lost data isn't mistaken for an empty set. It doesn't round values.
199
+ `AnnotationPointArray` (`[number, number]`) types raw array-form ink points.
200
+
201
+ ### Writing ink points in array form (`inkPointFormat`)
202
+
203
+ Whenever an annotation set is written, each ink coordinate is rounded to 0.1 pt and consecutive
204
+ duplicate ink points are dropped. By default ink points are still written in object form, which
205
+ every release can read. Set `inkPointFormat="array"` to write them in the shorter array form
206
+ instead; the clean-up is the same, the output is identical on iOS, Android and web, and
207
+ `version` stays at 1.
208
+
209
+ ```tsx
210
+ <ExpoPdfMarkupView
211
+ source={pdfPath}
212
+ annotations={annotations}
213
+ inkPointFormat="array"
214
+ onAnnotationsChanged={({ nativeEvent }) => setAnnotations(nativeEvent.annotations)}
215
+ />
216
+ ```
217
+
218
+ **Rollout rule:** only choose `'array'` once every version of your app that might read the
219
+ annotation set includes the release of this library with the array-form readers. Earlier
220
+ releases can't read array form: iOS rejects the whole annotation set, Android throws and web
221
+ draws `NaN`. So ship a version of your app with this release first,
222
+ and switch to `'array'` once that is the oldest version still in use.
223
+
224
+ Changing `inkPointFormat` writes nothing and doesn't fire `onAnnotationsChanged`. It applies from
225
+ the next edit, when the whole annotation set is written in the chosen form, whichever form it was
226
+ loaded in. Loading an annotation set never rewrites it.
227
+
228
+ ### Highlighting and underlining on iOS
229
+
230
+ With `annotationMode="highlight"` or `"underline"`, drag one finger to mark a rectangular area on
231
+ any page, including scanned PDFs. Highlights cover the rectangle; underlines follow its lower
232
+ edge. The tools use area selection on text-bearing pages too, without snapping to text lines.
233
+
234
+ The active tool captures touch input so marking does not scroll the page. Set
235
+ `annotationMode="none"` to scroll, pinch to zoom, or turn pages by touch, then reselect the tool.
236
+ The `page` prop and book-mode hardware keys remain available while marking; navigating cancels
237
+ an unfinished drag. Cancelling a gesture or switching tools also discards the unfinished area.
238
+ These Swift changes require a native iOS rebuild; a JavaScript-only update cannot install them.
@@ -0,0 +1,2 @@
1
+ [*.kt]
2
+ ktlint_code_style = android_studio
@@ -0,0 +1,33 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = 'dev.terhoeven.expopdfmarkup'
7
+ version = '0.1.0'
8
+
9
+ android {
10
+ namespace "dev.terhoeven.expopdfmarkup"
11
+ defaultConfig {
12
+ versionCode 1
13
+ versionName "0.1.0"
14
+ }
15
+ lintOptions {
16
+ abortOnError false
17
+ }
18
+ sourceSets {
19
+ test.resources.srcDir '../fixtures'
20
+ }
21
+ }
22
+
23
+ dependencies {
24
+ testImplementation 'junit:junit:4.13.2'
25
+ testImplementation 'org.json:json:20231013'
26
+ }
27
+
28
+ tasks.withType(Test) {
29
+ testLogging {
30
+ events "passed", "failed", "skipped"
31
+ showStandardStreams = false
32
+ }
33
+ }
@@ -0,0 +1,2 @@
1
+ <manifest>
2
+ </manifest>
@@ -0,0 +1,85 @@
1
+ package dev.terhoeven.expopdfmarkup
2
+
3
+ object AnnotationGeometry {
4
+
5
+ fun outlineBounds(annotation: AnnotationModel): AnnotationBounds? = when (annotation.type) {
6
+ "ink" -> outlineBoundsForInk(annotation)
7
+ "highlight", "underline", "freeText", "text", "stamp" -> annotation.bounds
8
+ else -> null
9
+ }
10
+
11
+ fun clampTranslation(
12
+ annotation: AnnotationModel,
13
+ deltaX: Float,
14
+ deltaY: Float,
15
+ pageWidth: Float,
16
+ pageHeight: Float
17
+ ): AnnotationPoint {
18
+ val bounds = outlineBounds(annotation) ?: return AnnotationPoint(deltaX, deltaY)
19
+ val minDx = -bounds.x
20
+ val maxDx = pageWidth - (bounds.x + bounds.width)
21
+ val minDy = -bounds.y
22
+ val maxDy = pageHeight - (bounds.y + bounds.height)
23
+ return AnnotationPoint(
24
+ x = deltaX.coerceIn(minDx, maxDx),
25
+ y = deltaY.coerceIn(minDy, maxDy)
26
+ )
27
+ }
28
+
29
+ fun translate(annotation: AnnotationModel, deltaX: Float, deltaY: Float): AnnotationModel {
30
+ if (deltaX == 0f && deltaY == 0f) return annotation
31
+ return when (annotation.type) {
32
+ "ink" ->
33
+ annotation.copy(
34
+ paths =
35
+ annotation.paths?.map { stroke ->
36
+ stroke.map { point ->
37
+ AnnotationPoint(point.x + deltaX, point.y + deltaY)
38
+ }
39
+ }
40
+ )
41
+
42
+ "highlight", "underline", "freeText", "text", "stamp" -> {
43
+ val bounds = annotation.bounds ?: return annotation
44
+ annotation.copy(
45
+ bounds =
46
+ AnnotationBounds(
47
+ x = bounds.x + deltaX,
48
+ y = bounds.y + deltaY,
49
+ width = bounds.width,
50
+ height = bounds.height
51
+ )
52
+ )
53
+ }
54
+
55
+ else -> annotation
56
+ }
57
+ }
58
+
59
+ private fun outlineBoundsForInk(annotation: AnnotationModel): AnnotationBounds? {
60
+ val paths = annotation.paths ?: return null
61
+ var minX = Float.POSITIVE_INFINITY
62
+ var minY = Float.POSITIVE_INFINITY
63
+ var maxX = Float.NEGATIVE_INFINITY
64
+ var maxY = Float.NEGATIVE_INFINITY
65
+
66
+ for (stroke in paths) {
67
+ for (point in stroke) {
68
+ minX = minOf(minX, point.x)
69
+ minY = minOf(minY, point.y)
70
+ maxX = maxOf(maxX, point.x)
71
+ maxY = maxOf(maxY, point.y)
72
+ }
73
+ }
74
+
75
+ if (!minX.isFinite() || !minY.isFinite()) return null
76
+
77
+ val padding = maxOf(annotation.lineWidth ?: 2f, 10f)
78
+ return AnnotationBounds(
79
+ x = minX - padding,
80
+ y = minY - padding,
81
+ width = maxX - minX + padding * 2,
82
+ height = maxY - minY + padding * 2
83
+ )
84
+ }
85
+ }
@@ -0,0 +1,76 @@
1
+ package dev.terhoeven.expopdfmarkup
2
+
3
+ import kotlin.math.abs
4
+ import kotlin.math.max
5
+ import kotlin.math.sqrt
6
+
7
+ object AnnotationHitTester {
8
+
9
+ fun hitTest(
10
+ point: AnnotationPoint,
11
+ annotations: List<AnnotationModel>,
12
+ pageIndex: Int
13
+ ): AnnotationModel? {
14
+ // Return last (topmost) matching annotation
15
+ for (annotation in annotations.reversed()) {
16
+ if (annotation.page != pageIndex) continue
17
+ when (annotation.type) {
18
+ "ink" -> {
19
+ val tolerance = max(annotation.lineWidth ?: 2f, 10f)
20
+ if (hitTestInk(point, annotation, tolerance)) return annotation
21
+ }
22
+
23
+ "highlight", "underline", "freeText", "text", "stamp" -> {
24
+ val bounds = annotation.bounds ?: continue
25
+ if (bounds.contains(point)) return annotation
26
+ }
27
+ }
28
+ }
29
+ return null
30
+ }
31
+
32
+ private fun hitTestInk(
33
+ point: AnnotationPoint,
34
+ annotation: AnnotationModel,
35
+ tolerance: Float
36
+ ): Boolean {
37
+ val paths = annotation.paths ?: return false
38
+ for (stroke in paths) {
39
+ for (i in 0 until stroke.size - 1) {
40
+ if (distanceToSegment(point, stroke[i], stroke[i + 1]) <= tolerance) {
41
+ return true
42
+ }
43
+ }
44
+ // Also check single-point strokes
45
+ if (stroke.size == 1) {
46
+ val dx = point.x - stroke[0].x
47
+ val dy = point.y - stroke[0].y
48
+ if (sqrt(dx * dx + dy * dy) <= tolerance) return true
49
+ }
50
+ }
51
+ return false
52
+ }
53
+
54
+ internal fun distanceToSegment(
55
+ point: AnnotationPoint,
56
+ a: AnnotationPoint,
57
+ b: AnnotationPoint
58
+ ): Float {
59
+ val dx = b.x - a.x
60
+ val dy = b.y - a.y
61
+ val lenSq = dx * dx + dy * dy
62
+ if (lenSq == 0f) {
63
+ // a and b are the same point
64
+ val px = point.x - a.x
65
+ val py = point.y - a.y
66
+ return sqrt(px * px + py * py)
67
+ }
68
+ var t = ((point.x - a.x) * dx + (point.y - a.y) * dy) / lenSq
69
+ t = t.coerceIn(0f, 1f)
70
+ val projX = a.x + t * dx
71
+ val projY = a.y + t * dy
72
+ val ex = point.x - projX
73
+ val ey = point.y - projY
74
+ return sqrt(ex * ex + ey * ey)
75
+ }
76
+ }
@@ -0,0 +1,41 @@
1
+ package dev.terhoeven.expopdfmarkup
2
+
3
+ data class AnnotationPoint(val x: Float, val y: Float)
4
+
5
+ data class AnnotationBounds(val x: Float, val y: Float, val width: Float, val height: Float) {
6
+ fun contains(point: AnnotationPoint): Boolean =
7
+ point.x >= x && point.x <= x + width && point.y >= y && point.y <= y + height
8
+ }
9
+
10
+ data class AnnotationModel(
11
+ val id: String,
12
+ val type: String,
13
+ val page: Int,
14
+ val color: String,
15
+ val lineWidth: Float? = null,
16
+ val alpha: Float? = null,
17
+ val paths: List<List<AnnotationPoint>>? = null,
18
+ val bounds: AnnotationBounds? = null,
19
+ val contents: String? = null,
20
+ val fontSize: Float? = null,
21
+ val fontFamily: String? = null,
22
+ val createdAt: Double? = null,
23
+ val text: String? = null
24
+ )
25
+
26
+ data class AnnotationsData(
27
+ val version: Int = 1,
28
+ val annotations: List<AnnotationModel> = emptyList()
29
+ )
30
+
31
+ /** How ink points are written: object form `{"x": …, "y": …}` (default) or array form `[x, y]`. */
32
+ enum class InkPointFormat {
33
+ OBJECT,
34
+ ARRAY
35
+ ;
36
+
37
+ companion object {
38
+ /** Maps the `inkPointFormat` view prop; anything other than `"array"` is object form. */
39
+ fun fromProp(value: String?): InkPointFormat = if (value == "array") ARRAY else OBJECT
40
+ }
41
+ }