@tobyt/expo-pdf-markup 0.6.0 โ†’ 1.0.0

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @tobyt/expo-pdf-markup
2
2
 
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - ea50181: Stable 1.0.0 release โ€” production-ready API for displaying and annotating PDFs on iOS, Android, and Web.
8
+
9
+ ### Patch Changes
10
+
11
+ - 906ce89: Fix Android blank PDF and scroll position loss when navigating back to a screen containing the PDF view
12
+
13
+ ## 0.6.1
14
+
15
+ ### Patch Changes
16
+
17
+ - e1a942b: Fix Android custom font rendering
18
+
3
19
  ## 0.6.0
4
20
 
5
21
  ### Minor Changes
package/README.md CHANGED
@@ -9,8 +9,6 @@ An Expo module for displaying and annotating PDFs, with support for iOS, Android
9
9
 
10
10
  **[๐Ÿ“– API Reference](https://tobyt42.github.io/expo-pdf-markup/api/)** ยท **[๐Ÿš€ Example App](https://tobyt42.github.io/expo-pdf-markup/example/)**
11
11
 
12
- > **Status:** Early development โ€” actively tested in the [Choir](https://www.thechoirapp.com) app.
13
-
14
12
  ## Platform support
15
13
 
16
14
  | Platform | PDF rendering | Annotations |
@@ -152,6 +150,10 @@ npx expo start
152
150
  </tr>
153
151
  </table>
154
152
 
153
+ ## Used by
154
+
155
+ - [Choir](https://www.thechoirapp.com) โ€” a choir practice app for iOS, Android and Web
156
+
155
157
  ## License
156
158
 
157
159
  MIT
@@ -1,6 +1,7 @@
1
1
  package dev.terhoeven.expopdfmarkup
2
2
 
3
3
  import android.content.Context
4
+ import android.content.res.AssetManager
4
5
  import android.graphics.Canvas
5
6
  import android.graphics.DashPathEffect
6
7
  import android.graphics.Paint
@@ -171,14 +172,47 @@ object AnnotationRenderer {
171
172
  canvas.drawText(text, left, top + paint.textSize, paint)
172
173
  }
173
174
 
174
- /** Resolve a typeface by family name. Tries app assets first (where expo-font places fonts),
175
- * then falls back to system typeface resolution. */
175
+ /** Resolve a typeface the same way React Native text does when available, so
176
+ * expo-font loaded families are measured and rendered consistently with the
177
+ * rest of the app. */
176
178
  fun resolveTypeface(context: Context, fontFamily: String?): Typeface {
177
179
  if (fontFamily == null) return Typeface.DEFAULT
178
- return try {
179
- Typeface.createFromAsset(context.assets, "fonts/$fontFamily.ttf")
180
- } catch (_: Exception) {
181
- Typeface.create(fontFamily, Typeface.NORMAL)
180
+ return resolveReactTypeface(fontFamily, context.assets)
181
+ ?: try {
182
+ Typeface.createFromAsset(context.assets, "fonts/$fontFamily.ttf")
183
+ } catch (_: Exception) {
184
+ Typeface.create(fontFamily, Typeface.NORMAL)
185
+ }
186
+ }
187
+
188
+ private fun resolveReactTypeface(fontFamily: String, assetManager: AssetManager): Typeface? {
189
+ val managerClasses = listOf(
190
+ "com.facebook.react.common.assets.ReactFontManager",
191
+ "com.facebook.react.views.text.ReactFontManager"
192
+ )
193
+
194
+ for (className in managerClasses) {
195
+ try {
196
+ val managerClass = Class.forName(className)
197
+ val getInstance = managerClass.getMethod("getInstance")
198
+ val manager = getInstance.invoke(null)
199
+ val getTypeface = managerClass.getMethod(
200
+ "getTypeface",
201
+ String::class.java,
202
+ Int::class.javaPrimitiveType,
203
+ AssetManager::class.java
204
+ )
205
+ return getTypeface.invoke(
206
+ manager,
207
+ fontFamily,
208
+ Typeface.NORMAL,
209
+ assetManager
210
+ ) as? Typeface
211
+ } catch (_: Exception) {
212
+ continue
213
+ }
182
214
  }
215
+
216
+ return null
183
217
  }
184
218
  }
@@ -16,6 +16,14 @@ import android.widget.OverScroller
16
16
  import java.util.UUID
17
17
 
18
18
  class ContinuousPdfView(context: Context) : View(context) {
19
+ data class ScrollState(val panX: Float, val panY: Float, val scale: Float)
20
+
21
+ var pendingScrollRestore: ScrollState? = null
22
+
23
+ fun captureScrollState(): ScrollState? {
24
+ if (pageBitmaps.isEmpty()) return null
25
+ return ScrollState(panX, panY, currentScale)
26
+ }
19
27
  private val pageBitmaps = mutableListOf<Bitmap>()
20
28
  private val pageYOffsets = mutableListOf<Float>()
21
29
  private val pageWidths = mutableListOf<Int>()
@@ -131,6 +139,15 @@ class ContinuousPdfView(context: Context) : View(context) {
131
139
  panX = 0f
132
140
  panY = 0f
133
141
  lastNotifiedPage = -1
142
+
143
+ pendingScrollRestore?.let { state ->
144
+ currentScale = state.scale.coerceIn(minScale, maxScale)
145
+ panX = state.panX
146
+ panY = state.panY
147
+ constrainPan()
148
+ pendingScrollRestore = null
149
+ }
150
+
134
151
  invalidate()
135
152
  notifyPageChange()
136
153
  }
@@ -24,7 +24,10 @@ class ExpoPdfMarkupView(context: Context, appContext: AppContext) : ExpoView(con
24
24
  private var renderer: PdfRenderer? = null
25
25
  private var fileDescriptor: ParcelFileDescriptor? = null
26
26
  private var currentSource: String? = null
27
+ private var lastLoadedSource: String? = null
27
28
  private var pendingAnnotationsJson: String? = null
29
+ private var sourceToReloadOnAttach: String? = null
30
+ private var savedScrollState: ContinuousPdfView.ScrollState? = null
28
31
  var useJsTextDialog: Boolean = false
29
32
 
30
33
  private var pendingTextPage: Int = -1
@@ -65,6 +68,7 @@ class ExpoPdfMarkupView(context: Context, appContext: AppContext) : ExpoView(con
65
68
  }
66
69
 
67
70
  fun loadPdf(source: String) {
71
+ sourceToReloadOnAttach = null // Explicit load supersedes any pending reload-on-attach
68
72
  if (source == currentSource) return
69
73
  currentSource = source
70
74
 
@@ -79,6 +83,7 @@ class ExpoPdfMarkupView(context: Context, appContext: AppContext) : ExpoView(con
79
83
  fileDescriptor = fd
80
84
  val r = PdfRenderer(fd)
81
85
  renderer = r
86
+ lastLoadedSource = source
82
87
  onLoadComplete(mapOf("pageCount" to r.pageCount))
83
88
  if (width > 0) {
84
89
  pdfView.loadPages(r, width)
@@ -188,9 +193,24 @@ class ExpoPdfMarkupView(context: Context, appContext: AppContext) : ExpoView(con
188
193
 
189
194
  override fun onDetachedFromWindow() {
190
195
  super.onDetachedFromWindow()
196
+ // Save the successfully-loaded source before close() so we can reload on re-attach.
197
+ // (currentSource is always null after loadPdf() because close() resets it there.)
198
+ sourceToReloadOnAttach = lastLoadedSource
199
+ lastLoadedSource = null
200
+ savedScrollState = pdfView.captureScrollState()
191
201
  close()
192
202
  }
193
203
 
204
+ override fun onAttachedToWindow() {
205
+ super.onAttachedToWindow()
206
+ sourceToReloadOnAttach?.let { source ->
207
+ sourceToReloadOnAttach = null
208
+ pdfView.pendingScrollRestore = savedScrollState
209
+ savedScrollState = null
210
+ loadPdf(source)
211
+ }
212
+ }
213
+
194
214
  override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
195
215
  super.onSizeChanged(w, h, oldw, oldh)
196
216
  if (w > 0 && w != oldw) {
@@ -82,7 +82,7 @@ export type ExpoPdfMarkupViewProps = {
82
82
  /**
83
83
  * Default font family for new text annotations. Platform-specific:
84
84
  * - iOS: PostScript name (`"Georgia"`, `"Courier"`) or `undefined` for system font (San Francisco)
85
- * - Android: family name (`"serif"`, `"monospace"`) or `undefined` for default sans-serif
85
+ * - Android: React Native / Expo font family name (`"Montserrat-Regular"`, `"serif"`) or `undefined` for default sans-serif
86
86
  * - Web: CSS font family (`"Georgia, serif"`) or `undefined` for `sans-serif`
87
87
  */
88
88
  annotationFontFamily?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"ExpoPdfMarkup.types.js","sourceRoot":"","sources":["../src/ExpoPdfMarkup.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { StyleProp, ViewStyle } from 'react-native';\n\nexport type AnnotationPoint = { x: number; y: number };\n\nexport type AnnotationBounds = { x: number; y: number; width: number; height: number };\n\nexport type InkAnnotation = {\n id: string;\n type: 'ink';\n page: number;\n color: string;\n lineWidth: number;\n paths: AnnotationPoint[][];\n createdAt?: number;\n};\n\nexport type HighlightAnnotation = {\n id: string;\n type: 'highlight';\n page: number;\n color: string;\n alpha?: number;\n bounds: AnnotationBounds;\n createdAt?: number;\n};\n\nexport type UnderlineAnnotation = {\n id: string;\n type: 'underline';\n page: number;\n color: string;\n bounds: AnnotationBounds;\n createdAt?: number;\n};\n\nexport type TextAnnotation = {\n id: string;\n type: 'text' | 'freeText';\n page: number;\n color: string;\n bounds: AnnotationBounds;\n contents?: string;\n fontSize?: number;\n /**\n * Font family for the text annotation. Platform-specific:\n * - iOS: PostScript name (`\"Georgia\"`, `\"Courier\"`) or `undefined` for system font (San Francisco)\n * - Android: family name (`\"serif\"`, `\"monospace\"`) or `undefined` for default sans-serif\n * - Web: CSS font family (`\"Georgia, serif\"`) or `undefined` for `sans-serif`\n */\n fontFamily?: string;\n createdAt?: number;\n};\n\nexport type Annotation = InkAnnotation | HighlightAnnotation | UnderlineAnnotation | TextAnnotation;\n\nexport type AnnotationsData = {\n version: 1;\n annotations: Annotation[];\n};\n\nexport type AnnotationMode =\n | 'none'\n | 'ink'\n | 'highlight'\n | 'underline'\n | 'text'\n | 'eraser'\n | 'move';\n\nexport type TextInputRequest = {\n mode: 'create' | 'edit';\n page: number;\n point: AnnotationPoint;\n currentText?: string;\n};\n\nexport type ExpoPdfMarkupViewProps = {\n /** Absolute local file path of the PDF to display. */\n source: string;\n /** 0-based page number to display. Can be used to restore scroll position on orientation change. */\n page?: number;\n /** Background colour shown behind the PDF pages. */\n backgroundColor?: string;\n /** Serialised {@link AnnotationsData} JSON string to load when the document opens. */\n annotations?: string;\n /** Active annotation tool. Defaults to `'none'` (view-only). */\n annotationMode?: AnnotationMode;\n /** Colour applied to new annotations, as a CSS colour string (e.g. `'#FF0000'`). */\n annotationColor?: string;\n /** Stroke width in points applied to new ink annotations. */\n annotationLineWidth?: number;\n /**\n * Default font family for new text annotations. Platform-specific:\n * - iOS: PostScript name (`\"Georgia\"`, `\"Courier\"`) or `undefined` for system font (San Francisco)\n * - Android: family name (`\"serif\"`, `\"monospace\"`) or `undefined` for default sans-serif\n * - Web: CSS font family (`\"Georgia, serif\"`) or `undefined` for `sans-serif`\n */\n annotationFontFamily?: string;\n /** Fired when the visible page changes. */\n onPageChanged?: (event: {\n nativeEvent: { page: number; pageCount: number; pageWidth: number; pageHeight: number };\n }) => void;\n /** Fired once the document has finished loading. */\n onLoadComplete?: (event: { nativeEvent: { pageCount: number } }) => void;\n /** Fired when the document fails to load. */\n onError?: (event: { nativeEvent: { message: string } }) => void;\n /** Fired after annotations are created or edited. `annotations` is a serialised {@link AnnotationsData} JSON string. */\n onAnnotationsChanged?: (event: { nativeEvent: { annotations: string } }) => void;\n /**\n * Optional async callback for the text annotation tool. When provided, this is called instead of\n * the native platform dialog (UIAlertController / AlertDialog) when the user taps to place a text\n * annotation. When editing an existing text annotation, `request.currentText` is populated and\n * `request.mode` is `'edit'`. Return the text string to create/update the annotation, or `null`\n * to cancel.\n */\n onTextInputRequested?: (request: TextInputRequest) => Promise<string | null>;\n style?: StyleProp<ViewStyle>;\n};\n"]}
1
+ {"version":3,"file":"ExpoPdfMarkup.types.js","sourceRoot":"","sources":["../src/ExpoPdfMarkup.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { StyleProp, ViewStyle } from 'react-native';\n\nexport type AnnotationPoint = { x: number; y: number };\n\nexport type AnnotationBounds = { x: number; y: number; width: number; height: number };\n\nexport type InkAnnotation = {\n id: string;\n type: 'ink';\n page: number;\n color: string;\n lineWidth: number;\n paths: AnnotationPoint[][];\n createdAt?: number;\n};\n\nexport type HighlightAnnotation = {\n id: string;\n type: 'highlight';\n page: number;\n color: string;\n alpha?: number;\n bounds: AnnotationBounds;\n createdAt?: number;\n};\n\nexport type UnderlineAnnotation = {\n id: string;\n type: 'underline';\n page: number;\n color: string;\n bounds: AnnotationBounds;\n createdAt?: number;\n};\n\nexport type TextAnnotation = {\n id: string;\n type: 'text' | 'freeText';\n page: number;\n color: string;\n bounds: AnnotationBounds;\n contents?: string;\n fontSize?: number;\n /**\n * Font family for the text annotation. Platform-specific:\n * - iOS: PostScript name (`\"Georgia\"`, `\"Courier\"`) or `undefined` for system font (San Francisco)\n * - Android: family name (`\"serif\"`, `\"monospace\"`) or `undefined` for default sans-serif\n * - Web: CSS font family (`\"Georgia, serif\"`) or `undefined` for `sans-serif`\n */\n fontFamily?: string;\n createdAt?: number;\n};\n\nexport type Annotation = InkAnnotation | HighlightAnnotation | UnderlineAnnotation | TextAnnotation;\n\nexport type AnnotationsData = {\n version: 1;\n annotations: Annotation[];\n};\n\nexport type AnnotationMode =\n | 'none'\n | 'ink'\n | 'highlight'\n | 'underline'\n | 'text'\n | 'eraser'\n | 'move';\n\nexport type TextInputRequest = {\n mode: 'create' | 'edit';\n page: number;\n point: AnnotationPoint;\n currentText?: string;\n};\n\nexport type ExpoPdfMarkupViewProps = {\n /** Absolute local file path of the PDF to display. */\n source: string;\n /** 0-based page number to display. Can be used to restore scroll position on orientation change. */\n page?: number;\n /** Background colour shown behind the PDF pages. */\n backgroundColor?: string;\n /** Serialised {@link AnnotationsData} JSON string to load when the document opens. */\n annotations?: string;\n /** Active annotation tool. Defaults to `'none'` (view-only). */\n annotationMode?: AnnotationMode;\n /** Colour applied to new annotations, as a CSS colour string (e.g. `'#FF0000'`). */\n annotationColor?: string;\n /** Stroke width in points applied to new ink annotations. */\n annotationLineWidth?: number;\n /**\n * Default font family for new text annotations. Platform-specific:\n * - iOS: PostScript name (`\"Georgia\"`, `\"Courier\"`) or `undefined` for system font (San Francisco)\n * - Android: React Native / Expo font family name (`\"Montserrat-Regular\"`, `\"serif\"`) or `undefined` for default sans-serif\n * - Web: CSS font family (`\"Georgia, serif\"`) or `undefined` for `sans-serif`\n */\n annotationFontFamily?: string;\n /** Fired when the visible page changes. */\n onPageChanged?: (event: {\n nativeEvent: { page: number; pageCount: number; pageWidth: number; pageHeight: number };\n }) => void;\n /** Fired once the document has finished loading. */\n onLoadComplete?: (event: { nativeEvent: { pageCount: number } }) => void;\n /** Fired when the document fails to load. */\n onError?: (event: { nativeEvent: { message: string } }) => void;\n /** Fired after annotations are created or edited. `annotations` is a serialised {@link AnnotationsData} JSON string. */\n onAnnotationsChanged?: (event: { nativeEvent: { annotations: string } }) => void;\n /**\n * Optional async callback for the text annotation tool. When provided, this is called instead of\n * the native platform dialog (UIAlertController / AlertDialog) when the user taps to place a text\n * annotation. When editing an existing text annotation, `request.currentText` is populated and\n * `request.mode` is `'edit'`. Return the text string to create/update the annotation, or `null`\n * to cancel.\n */\n onTextInputRequested?: (request: TextInputRequest) => Promise<string | null>;\n style?: StyleProp<ViewStyle>;\n};\n"]}
@@ -241,18 +241,40 @@ enum AnnotationSerializer {
241
241
 
242
242
  private static func createFreeTextAnnotation(model: AnnotationModel, color: UIColor) -> PDFAnnotation? {
243
243
  guard let bounds = model.bounds else { return nil }
244
- let annotation = PDFAnnotation(bounds: bounds.cgRect, forType: .freeText, withProperties: nil)
245
244
  let fontSize = model.fontSize ?? 16.0
246
- annotation.font = UIFont(name: model.fontFamily ?? "", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)
245
+ let font = UIFont(name: model.fontFamily ?? "", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)
246
+ let contents = model.contents ?? ""
247
+ let annotation = PDFAnnotation(
248
+ bounds: normalizedFreeTextBounds(bounds: bounds.cgRect, text: contents, font: font),
249
+ forType: .freeText,
250
+ withProperties: nil
251
+ )
252
+ annotation.font = font
247
253
  annotation.fontColor = color
248
254
  annotation.color = .clear
249
- annotation.contents = model.contents ?? ""
255
+ annotation.contents = contents
250
256
 
251
257
  let createdAt = model.createdAt ?? Date().timeIntervalSince1970
252
258
  tagAsModuleManaged(annotation, id: model.id, createdAt: createdAt, colorHex: model.color)
253
259
  return annotation
254
260
  }
255
261
 
262
+ private static func normalizedFreeTextBounds(bounds: CGRect, text: String, font: UIFont) -> CGRect {
263
+ guard !text.isEmpty else { return bounds }
264
+
265
+ let padding: CGFloat = 4.0
266
+ let textSize = (text as NSString).size(withAttributes: [.font: font])
267
+ let width = max(bounds.width, ceil(textSize.width + padding * 2))
268
+ let height = max(bounds.height, ceil(textSize.height + padding * 2))
269
+
270
+ return CGRect(
271
+ x: bounds.minX,
272
+ y: bounds.maxY - height,
273
+ width: width,
274
+ height: height
275
+ )
276
+ }
277
+
256
278
  private static func pointsFromBezierPath(_ path: UIBezierPath) -> [CGPoint] {
257
279
  var points: [CGPoint] = []
258
280
  let cgPath = path.cgPath
@@ -73,6 +73,24 @@ final class AnnotationSerializerTests: XCTestCase {
73
73
  XCTAssertEqual(annotation?.color, .clear)
74
74
  }
75
75
 
76
+ func testCreateFreeTextAnnotationExpandsNarrowBoundsToFitText() {
77
+ let originalBounds = AnnotationBounds(x: 100, y: 200, width: 40, height: 24)
78
+ let model = AnnotationModel(
79
+ id: "txt-narrow-1",
80
+ type: "freeText",
81
+ page: 0,
82
+ color: "#00FF00",
83
+ bounds: originalBounds,
84
+ contents: "Hello from Android",
85
+ fontSize: 16.0
86
+ )
87
+
88
+ let annotation = AnnotationSerializer.toPDFAnnotation(model)
89
+ XCTAssertNotNil(annotation)
90
+ XCTAssertGreaterThan(annotation?.bounds.width ?? 0, originalBounds.width)
91
+ XCTAssertEqual(annotation?.bounds.maxY, originalBounds.cgRect.maxY, accuracy: 0.01)
92
+ }
93
+
76
94
  func testUnknownTypeReturnsNil() {
77
95
  let model = AnnotationModel(
78
96
  id: "bad-1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tobyt/expo-pdf-markup",
3
- "version": "0.6.0",
3
+ "version": "1.0.0",
4
4
  "description": "An Expo module for displaying and annotating PDFs",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -92,7 +92,7 @@ export type ExpoPdfMarkupViewProps = {
92
92
  /**
93
93
  * Default font family for new text annotations. Platform-specific:
94
94
  * - iOS: PostScript name (`"Georgia"`, `"Courier"`) or `undefined` for system font (San Francisco)
95
- * - Android: family name (`"serif"`, `"monospace"`) or `undefined` for default sans-serif
95
+ * - Android: React Native / Expo font family name (`"Montserrat-Regular"`, `"serif"`) or `undefined` for default sans-serif
96
96
  * - Web: CSS font family (`"Georgia, serif"`) or `undefined` for `sans-serif`
97
97
  */
98
98
  annotationFontFamily?: string;