pdfkit-rs 0.2.4

Safe Rust bindings for Apple's PDFKit framework — documents, pages, selections, outlines, annotations, destinations, actions, and view state on macOS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
import Foundation
import PDFKit

private func pdf_document_info(_ document: PDFDocument) -> [String: Any] {
    [
        "document_url": document.documentURL?.path as Any,
        "major_version": document.majorVersion,
        "minor_version": document.minorVersion,
        "is_encrypted": document.isEncrypted,
        "is_locked": document.isLocked,
        "permissions_status": document.permissionsStatus.rawValue,
        "access_permissions": document.accessPermissions.rawValue,
        "allows_printing": document.allowsPrinting,
        "allows_copying": document.allowsCopying,
        "allows_document_changes": document.allowsDocumentChanges,
        "allows_document_assembly": document.allowsDocumentAssembly,
        "allows_content_accessibility": document.allowsContentAccessibility,
        "allows_commenting": document.allowsCommenting,
        "allows_form_field_entry": document.allowsFormFieldEntry,
        "page_class": NSStringFromClass(document.pageClass),
    ]
}

private func pdf_document_attributes(_ document: PDFDocument) -> [String: Any] {
    let attributes = document.documentAttributes ?? [:]
    let formatter = ISO8601DateFormatter()
    return [
        "title": attributes[PDFDocumentAttribute.titleAttribute] as? String as Any,
        "author": attributes[PDFDocumentAttribute.authorAttribute] as? String as Any,
        "subject": attributes[PDFDocumentAttribute.subjectAttribute] as? String as Any,
        "creator": attributes[PDFDocumentAttribute.creatorAttribute] as? String as Any,
        "producer": attributes[PDFDocumentAttribute.producerAttribute] as? String as Any,
        "creation_date": (attributes[PDFDocumentAttribute.creationDateAttribute] as? Date).map(formatter.string(from:)) as Any,
        "modification_date": (attributes[PDFDocumentAttribute.modificationDateAttribute] as? Date).map(formatter.string(from:)) as Any,
        "keywords": attributes[PDFDocumentAttribute.keywordsAttribute] as? [String] as Any,
    ]
}

private func pdf_document_write_options(_ json: String?) throws -> [PDFDocumentWriteOption: Any] {
    guard let json, !json.isEmpty else { return [:] }
    guard let data = json.data(using: .utf8) else {
        throw PDFBridgeError.invalidArgument("invalid write options JSON")
    }
    guard let payload = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
        throw PDFBridgeError.invalidArgument("invalid write options JSON")
    }

    var options: [PDFDocumentWriteOption: Any] = [:]

    if let ownerPassword = payload["owner_password"] as? String {
        options[PDFDocumentWriteOption.ownerPasswordOption] = ownerPassword
    }
    if let userPassword = payload["user_password"] as? String {
        options[PDFDocumentWriteOption.userPasswordOption] = userPassword
    }
    if let accessPermissions = payload["access_permissions"] as? NSNumber {
        if #available(macOS 12.0, *) {
            options[PDFDocumentWriteOption.accessPermissionsOption] = NSNumber(value: accessPermissions.uint64Value)
        } else {
            throw PDFBridgeError.framework("PDFDocumentAccessPermissionsOption requires macOS 12.0")
        }
    }
    if let burnInAnnotations = payload["burn_in_annotations"] as? Bool, burnInAnnotations {
        if #available(macOS 13.0, *) {
            options[PDFDocumentWriteOption.burnInAnnotationsOption] = NSNumber(value: true)
        } else {
            throw PDFBridgeError.framework("PDFDocumentBurnInAnnotationsOption requires macOS 13.0")
        }
    }
    if let saveTextFromOCR = payload["save_text_from_ocr"] as? Bool, saveTextFromOCR {
        if #available(macOS 13.0, *) {
            options[PDFDocumentWriteOption.saveTextFromOCROption] = NSNumber(value: true)
        } else {
            throw PDFBridgeError.framework("PDFDocumentSaveTextFromOCROption requires macOS 13.0")
        }
    }
    if let saveImagesAsJPEG = payload["save_images_as_jpeg"] as? Bool, saveImagesAsJPEG {
        if #available(macOS 13.4, *) {
            options[PDFDocumentWriteOption.saveImagesAsJPEGOption] = NSNumber(value: true)
        } else {
            throw PDFBridgeError.framework("PDFDocumentSaveImagesAsJPEGOption requires macOS 13.4")
        }
    }
    if let optimizeImagesForScreen = payload["optimize_images_for_screen"] as? Bool, optimizeImagesForScreen {
        if #available(macOS 13.4, *) {
            options[PDFDocumentWriteOption.optimizeImagesForScreenOption] = NSNumber(value: true)
        } else {
            throw PDFBridgeError.framework("PDFDocumentOptimizeImagesForScreenOption requires macOS 13.4")
        }
    }

    return options
}

@_cdecl("pdf_document_new")
public func pdf_document_new(
    _ outDocument: UnsafeMutablePointer<UnsafeMutableRawPointer?>?,
    _ outError: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
) -> Int32 {
    pdf_run(outError) {
        guard let outDocument else {
            throw PDFBridgeError.invalidArgument("missing document output pointer")
        }
        outDocument.pointee = pdf_retain_document(PDFDocument())
    }
}

@_cdecl("pdf_document_new_with_url")
public func pdf_document_new_with_url(
    _ path: UnsafePointer<CChar>?,
    _ outDocument: UnsafeMutablePointer<UnsafeMutableRawPointer?>?,
    _ outError: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
) -> Int32 {
    pdf_run(outError) {
        guard let path, let outDocument else {
            throw PDFBridgeError.invalidArgument("missing PDF path or output pointer")
        }
        let url = URL(fileURLWithPath: String(cString: path))
        guard let document = PDFDocument(url: url) else {
            throw PDFBridgeError.nullResult("PDFDocument(url:) returned nil")
        }
        outDocument.pointee = pdf_retain_document(document)
    }
}

@_cdecl("pdf_document_new_with_data")
public func pdf_document_new_with_data(
    _ bytes: UnsafePointer<UInt8>?,
    _ len: Int,
    _ outDocument: UnsafeMutablePointer<UnsafeMutableRawPointer?>?,
    _ outError: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
) -> Int32 {
    pdf_run(outError) {
        guard let bytes, len > 0, let outDocument else {
            throw PDFBridgeError.invalidArgument("missing PDF bytes or output pointer")
        }
        let data = Data(bytes: bytes, count: len)
        guard let document = PDFDocument(data: data) else {
            throw PDFBridgeError.nullResult("PDFDocument(data:) returned nil")
        }
        outDocument.pointee = pdf_retain_document(document)
    }
}

@_cdecl("pdf_document_info_json")
public func pdf_document_info_json(_ handle: UnsafeMutableRawPointer?) -> UnsafeMutablePointer<CChar>? {
    guard let document = pdf_document_value(handle) else { return nil }
    return pdf_string(pdf_json_string(from: pdf_document_info(document)) ?? "{}")
}

@_cdecl("pdf_document_attributes_json")
public func pdf_document_attributes_json(_ handle: UnsafeMutableRawPointer?) -> UnsafeMutablePointer<CChar>? {
    guard let document = pdf_document_value(handle) else { return nil }
    return pdf_string(pdf_json_string(from: pdf_document_attributes(document)) ?? "{}")
}

@_cdecl("pdf_document_string")
public func pdf_document_string(_ handle: UnsafeMutableRawPointer?) -> UnsafeMutablePointer<CChar>? {
    guard let document = pdf_document_value(handle), let string = document.string else {
        return nil
    }
    return pdf_string(string)
}

@_cdecl("pdf_document_page_count")
public func pdf_document_page_count(_ handle: UnsafeMutableRawPointer?) -> UInt64 {
    guard let document = pdf_document_value(handle) else { return 0 }
    return UInt64(document.pageCount)
}

@_cdecl("pdf_document_page_at")
public func pdf_document_page_at(
    _ handle: UnsafeMutableRawPointer?,
    _ index: UInt64
) -> UnsafeMutableRawPointer? {
    guard let document = pdf_document_value(handle),
          index < UInt64(document.pageCount),
          let page = document.page(at: Int(index))
    else {
        return nil
    }
    return pdf_retain_page(page)
}

@_cdecl("pdf_document_index_for_page")
public func pdf_document_index_for_page(
    _ documentHandle: UnsafeMutableRawPointer?,
    _ pageHandle: UnsafeMutableRawPointer?
) -> UInt64 {
    guard let document = pdf_document_value(documentHandle), let page = pdf_page_value(pageHandle) else {
        return UInt64.max
    }
    let index = document.index(for: page)
    return index == NSNotFound ? UInt64.max : UInt64(index)
}

@_cdecl("pdf_document_outline_root")
public func pdf_document_outline_root(_ handle: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? {
    guard let document = pdf_document_value(handle), let outline = document.outlineRoot else {
        return nil
    }
    return pdf_retain_outline(outline)
}

@_cdecl("pdf_document_set_outline_root")
public func pdf_document_set_outline_root(
    _ documentHandle: UnsafeMutableRawPointer?,
    _ outlineHandle: UnsafeMutableRawPointer?,
    _ outError: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
) -> Int32 {
    pdf_run(outError) {
        guard let document = pdf_document_value(documentHandle) else {
            throw PDFBridgeError.invalidArgument("missing document handle")
        }
        document.outlineRoot = pdf_outline_value(outlineHandle)
    }
}

@_cdecl("pdf_document_outline_item_for_selection")
public func pdf_document_outline_item_for_selection(
    _ documentHandle: UnsafeMutableRawPointer?,
    _ selectionHandle: UnsafeMutableRawPointer?
) -> UnsafeMutableRawPointer? {
    guard let document = pdf_document_value(documentHandle),
          let selection = pdf_selection_value(selectionHandle),
          let outline = document.outlineItem(for: selection)
    else {
        return nil
    }
    return pdf_retain_outline(outline)
}

@_cdecl("pdf_document_selection_for_entire_document")
public func pdf_document_selection_for_entire_document(_ handle: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? {
    guard let document = pdf_document_value(handle), let selection = document.selectionForEntireDocument else {
        return nil
    }
    return pdf_retain_selection(selection)
}

@_cdecl("pdf_document_selection_from_pages_points")
public func pdf_document_selection_from_pages_points(
    _ documentHandle: UnsafeMutableRawPointer?,
    _ startPageHandle: UnsafeMutableRawPointer?,
    _ startX: Double,
    _ startY: Double,
    _ endPageHandle: UnsafeMutableRawPointer?,
    _ endX: Double,
    _ endY: Double
) -> UnsafeMutableRawPointer? {
    guard let document = pdf_document_value(documentHandle),
          let startPage = pdf_page_value(startPageHandle),
          let endPage = pdf_page_value(endPageHandle)
    else {
        return nil
    }
    guard startPage.document === document, endPage.document === document else { return nil }
    let selection = document.selection(
        from: startPage,
        at: CGPoint(x: startX, y: startY),
        to: endPage,
        at: CGPoint(x: endX, y: endY)
    )
    return selection.map(pdf_retain_selection)
}

@_cdecl("pdf_document_selection_from_pages_points_with_granularity")
public func pdf_document_selection_from_pages_points_with_granularity(
    _ documentHandle: UnsafeMutableRawPointer?,
    _ startPageHandle: UnsafeMutableRawPointer?,
    _ startX: Double,
    _ startY: Double,
    _ endPageHandle: UnsafeMutableRawPointer?,
    _ endX: Double,
    _ endY: Double,
    _ granularityRaw: UInt64
) -> UnsafeMutableRawPointer? {
    guard let document = pdf_document_value(documentHandle),
          let startPage = pdf_page_value(startPageHandle),
          let endPage = pdf_page_value(endPageHandle)
    else {
        return nil
    }
    guard startPage.document === document, endPage.document === document else { return nil }
    guard let granularity = PDFSelectionGranularity(rawValue: UInt(granularityRaw)) else {
        return nil
    }
    if #available(macOS 15.0, *) {
        let selection = document.selection(
            from: startPage,
            at: CGPoint(x: startX, y: startY),
            to: endPage,
            at: CGPoint(x: endX, y: endY),
            with: granularity
        )
        return selection.map(pdf_retain_selection)
    }
    return nil
}

@_cdecl("pdf_document_selection_from_pages_characters")
public func pdf_document_selection_from_pages_characters(
    _ documentHandle: UnsafeMutableRawPointer?,
    _ startPageHandle: UnsafeMutableRawPointer?,
    _ startCharacter: UInt64,
    _ endPageHandle: UnsafeMutableRawPointer?,
    _ endCharacter: UInt64
) -> UnsafeMutableRawPointer? {
    guard let document = pdf_document_value(documentHandle),
          let startPage = pdf_page_value(startPageHandle),
          let endPage = pdf_page_value(endPageHandle)
    else {
        return nil
    }
    guard startPage.document === document, endPage.document === document else { return nil }
    let selection = document.selection(
        from: startPage,
        atCharacterIndex: Int(startCharacter),
        to: endPage,
        atCharacterIndex: Int(endCharacter)
    )
    return selection.map(pdf_retain_selection)
}

@_cdecl("pdf_document_unlock")
public func pdf_document_unlock(
    _ handle: UnsafeMutableRawPointer?,
    _ password: UnsafePointer<CChar>?
) -> Int32 {
    guard let document = pdf_document_value(handle), let password else {
        return 0
    }
    return document.unlock(withPassword: String(cString: password)) ? 1 : 0
}

@_cdecl("pdf_document_set_delegate")
public func pdf_document_set_delegate(
    _ handle: UnsafeMutableRawPointer?,
    _ delegateHandle: UnsafeMutableRawPointer?,
    _ outError: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
) -> Int32 {
    pdf_run(outError) {
        guard let document = pdf_document_value(handle) else {
            throw PDFBridgeError.invalidArgument("missing document handle")
        }
        document.delegate = pdf_document_delegate_value(delegateHandle)
    }
}

@_cdecl("pdf_document_write_to_url")
public func pdf_document_write_to_url(
    _ handle: UnsafeMutableRawPointer?,
    _ path: UnsafePointer<CChar>?,
    _ outError: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
) -> Int32 {
    pdf_run(outError) {
        guard let document = pdf_document_value(handle), let path else {
            throw PDFBridgeError.invalidArgument("missing document handle or output path")
        }
        let url = URL(fileURLWithPath: String(cString: path))
        guard document.write(to: url) else {
            throw PDFBridgeError.nullResult("PDFDocument.write(to:) returned false")
        }
    }
}

@_cdecl("pdf_document_write_to_url_with_options")
public func pdf_document_write_to_url_with_options(
    _ handle: UnsafeMutableRawPointer?,
    _ path: UnsafePointer<CChar>?,
    _ optionsJSON: UnsafePointer<CChar>?,
    _ outError: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
) -> Int32 {
    pdf_run(outError) {
        guard let document = pdf_document_value(handle), let path else {
            throw PDFBridgeError.invalidArgument("missing document handle or output path")
        }
        let options = try pdf_document_write_options(pdf_optional_string(optionsJSON))
        let url = URL(fileURLWithPath: String(cString: path))
        guard document.write(to: url, withOptions: options.isEmpty ? nil : options) else {
            throw PDFBridgeError.nullResult("PDFDocument.write(to:withOptions:) returned false")
        }
    }
}

@_cdecl("pdf_document_insert_page")
public func pdf_document_insert_page(
    _ documentHandle: UnsafeMutableRawPointer?,
    _ pageHandle: UnsafeMutableRawPointer?,
    _ index: UInt64,
    _ outError: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
) -> Int32 {
    pdf_run(outError) {
        guard let document = pdf_document_value(documentHandle), let page = pdf_page_value(pageHandle) else {
            throw PDFBridgeError.invalidArgument("missing document or page handle")
        }
        guard index <= UInt64(document.pageCount) else {
            throw PDFBridgeError.invalidArgument("page index out of range")
        }
        document.insert(page, at: Int(index))
    }
}

@_cdecl("pdf_document_remove_page_at")
public func pdf_document_remove_page_at(
    _ documentHandle: UnsafeMutableRawPointer?,
    _ index: UInt64,
    _ outError: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
) -> Int32 {
    pdf_run(outError) {
        guard let document = pdf_document_value(documentHandle) else {
            throw PDFBridgeError.invalidArgument("missing document handle")
        }
        guard index < UInt64(document.pageCount) else {
            throw PDFBridgeError.invalidArgument("page index out of range")
        }
        document.removePage(at: Int(index))
    }
}

@_cdecl("pdf_document_exchange_pages")
public func pdf_document_exchange_pages(
    _ documentHandle: UnsafeMutableRawPointer?,
    _ indexA: UInt64,
    _ indexB: UInt64,
    _ outError: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
) -> Int32 {
    pdf_run(outError) {
        guard let document = pdf_document_value(documentHandle) else {
            throw PDFBridgeError.invalidArgument("missing document handle")
        }
        guard indexA < UInt64(document.pageCount), indexB < UInt64(document.pageCount) else {
            throw PDFBridgeError.invalidArgument("page index out of range")
        }
        guard let pageA = document.page(at: Int(indexA)),
              let pageB = document.page(at: Int(indexB)),
              pageA.pageRef != nil,
              pageB.pageRef != nil
        else {
            throw PDFBridgeError.invalidArgument("PDFDocument.exchangePage is unsupported for synthetic in-memory pages")
        }
        document.exchangePage(at: Int(indexA), withPageAt: Int(indexB))
    }
}