Debian Codegraph @

platform/wasm/lib/mupdf.ts

raw
1 // Copyright (C) 2004-2025 Artifex Software, Inc.
2 //
3 // This file is part of MuPDF WASM Library.
4 //
5 // MuPDF is free software: you can redistribute it and/or modify it under the
6 // terms of the GNU Affero General Public License as published by the Free
7 // Software Foundation, either version 3 of the License, or (at your option)
8 // any later version.
9 //
10 // MuPDF is distributed in the hope that it will be useful, but WITHOUT ANY
11 // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 // FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
13 // details.
14 //
15 // You should have received a copy of the GNU Affero General Public License
16 // along with MuPDF. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>
17 //
18 // Alternative licensing terms are available from the licensor.
19 // For commercial licensing, see <https://www.artifex.com/> or contact
20 // Artifex Software, Inc., 39 Mesa Street, Suite 108A, San Francisco,
21 // CA 94129, USA, for further information.
22
23 "use strict"
24
25 import { Pointer } from "./mupdf-wasm.js"
26 import libmupdf_wasm from "./mupdf-wasm.js"
27
28 declare global {
29 var $libmupdf_wasm_Module: any
30 }
31
32 var node_fs: any = null
33 if (typeof process !== "undefined" && process.versions && process.versions.node)
34 node_fs = await import("node:fs")
35
36 const libmupdf = await libmupdf_wasm(globalThis["$libmupdf_wasm_Module"])
37
38 libmupdf._wasm_init_context()
39
40 function Malloc<T>(size: number) {
41 return libmupdf._wasm_malloc(size) as unknown as Pointer<T>
42 }
43
44 function Free(ptr: any) {
45 libmupdf._wasm_free(ptr as Pointer<"void">)
46 }
47
48 export const memento = {
49 listBlocks() {
50 libmupdf._wasm_Memento_listBlocks()
51 },
52 checkAllMemory() {
53 libmupdf._wasm_Memento_checkAllMemory()
54 },
55 }
56
57 /*
58 --------------------------------------------------------------------------------
59
60 How to call into WASM and convert values between JS and WASM (libmupdf) worlds:
61
62 Passing values into WASM needs to either copy primitive values into WASM memory
63 or passing around pointer values.
64
65 Wrap and/or copy non-Userdata values into WASM:
66
67 STRING(stringValue)
68 STRING2(stringValue) -- if you need to pass more than one string
69 MATRIX(matrixArray)
70 RECT(rectArray)
71 BUFFER(bufferValue)
72 etc.
73
74 Look up an enum value by string:
75
76 ENUM<EnumType>(string, listOfValidValues)
77
78 Pass the pointer when the value is a Userdata object:
79
80 userdataObject.pointer
81
82 Convert WASM pointer into a JS value (for simple types like strings and matrices).
83
84 fromType(pointer)
85
86 Wrap a WASM pointer in a new Userdata object (for complex types):
87
88 new Wrapper(pointer)
89
90 PDFObjects are always bound to a PDFDocument, so must be accessed via a document:
91
92 doc._fromPDFObjectNew(new_ptr)
93 doc._fromPDFObjectKeep(borrowed_ptr)
94 doc._PDFOBJ(value)
95
96 Type checking of input arguments at runtime.
97
98 checkType(value, "string")
99 checkType(value, Class)
100 checkRect(value)
101 checkMatrix(value)
102
103 This code needs to work type safely from plain Javascript too,
104 so do NOT rely on Typescript to do all the type checking.
105
106 --------------------------------------------------------------------------------
107 */
108
109 export type Matrix = [number, number, number, number, number, number]
110 export type Rect = [number, number, number, number]
111 export type Quad = [number, number, number, number, number, number, number, number]
112 export type Point = [number, number]
113 export type Color = [number] | [number, number, number] | [number, number, number, number]
114 export type AnnotColor = [] | Color
115
116 export type Rotate = 0 | 90 | 180 | 270
117
118 export const Matrix = {
119 identity: [ 1, 0, 0, 1, 0, 0 ] as Matrix,
120 scale(sx: number, sy: number): Matrix {
121 return [ sx, 0, 0, sy, 0, 0 ]
122 },
123 translate(tx: number, ty: number): Matrix {
124 return [ 1, 0, 0, 1, tx, ty ]
125 },
126 rotate(d: number): Matrix {
127 while (d < 0)
128 d += 360
129 while (d >= 360)
130 d -= 360
131 let s = Math.sin((d * Math.PI) / 180)
132 let c = Math.cos((d * Math.PI) / 180)
133 return [ c, s, -s, c, 0, 0 ]
134 },
135 invert(m: Matrix): Matrix {
136 checkMatrix(m)
137 let det = m[0] * m[3] - m[1] * m[2]
138 if (det > -1e-23 && det < 1e-23)
139 return m
140 let rdet = 1 / det
141 let inva = m[3] * rdet
142 let invb = -m[1] * rdet
143 let invc = -m[2] * rdet
144 let invd = m[0] * rdet
145 let inve = -m[4] * inva - m[5] * invc
146 let invf = -m[4] * invb - m[5] * invd
147 return [ inva, invb, invc, invd, inve, invf ]
148 },
149 concat(one: Matrix, two: Matrix): Matrix {
150 checkMatrix(one)
151 checkMatrix(two)
152 return [
153 one[0] * two[0] + one[1] * two[2],
154 one[0] * two[1] + one[1] * two[3],
155 one[2] * two[0] + one[3] * two[2],
156 one[2] * two[1] + one[3] * two[3],
157 one[4] * two[0] + one[5] * two[2] + two[4],
158 one[4] * two[1] + one[5] * two[3] + two[5],
159 ]
160 },
161 }
162
163 export const Rect = {
164 MIN_INF_RECT: 0x80000000,
165 MAX_INF_RECT: 0x7fffff80,
166 empty: [ 0x80000000, 0x80000000, 0x7fffff80, 0x7fffff80 ],
167 invalid: [ 0, 0, -1, -1 ],
168 infinite: [ 0x7fffff80, 0x7fffff80, 0x80000000, 0x80000000 ],
169 isEmpty: function (rect: Rect) {
170 checkRect(rect)
171 return rect[0] >= rect[2] || rect[1] >= rect[3]
172 },
173 isValid: function (rect: Rect) {
174 checkRect(rect)
175 return rect[0] <= rect[2] && rect[1] <= rect[3]
176 },
177 isInfinite: function (rect: Rect) {
178 checkRect(rect)
179 return (
180 rect[0] === Rect.MAX_INF_RECT &&
181 rect[1] === Rect.MAX_INF_RECT &&
182 rect[2] === Rect.MIN_INF_RECT &&
183 rect[3] === Rect.MIN_INF_RECT
184 )
185 },
186 transform: function (rect: Rect, matrix: Matrix): Rect {
187 checkRect(rect)
188 checkMatrix(matrix)
189 var t
190
191 if (Rect.isInfinite(rect))
192 return rect
193 if (!Rect.isValid(rect))
194 return rect
195
196 var ax0 = rect[0] * matrix[0]
197 var ax1 = rect[2] * matrix[0]
198 if (ax0 > ax1)
199 t = ax0, ax0 = ax1, ax1 = t
200
201 var cy0 = rect[1] * matrix[2]
202 var cy1 = rect[3] * matrix[2]
203 if (cy0 > cy1)
204 t = cy0, cy0 = cy1, cy1 = t
205
206 ax0 += cy0 + matrix[4]
207 ax1 += cy1 + matrix[4]
208
209 var bx0 = rect[0] * matrix[1]
210 var bx1 = rect[2] * matrix[1]
211 if (bx0 > bx1)
212 t = bx0, bx0 = bx1, bx1 = t
213
214 var dy0 = rect[1] * matrix[3]
215 var dy1 = rect[3] * matrix[3]
216 if (dy0 > dy1)
217 t = dy0, dy0 = dy1, dy1 = t
218
219 bx0 += dy0 + matrix[5]
220 bx1 += dy1 + matrix[5]
221
222 return [ ax0, bx0, ax1, bx1 ]
223 },
224 }
225
226 export function enableICC() {
227 libmupdf._wasm_enable_icc()
228 }
229
230 export function disableICC() {
231 libmupdf._wasm_disable_icc()
232 }
233
234 export function setUserCSS(text: string) {
235 libmupdf._wasm_set_user_css(STRING(text))
236 }
237
238 export function emptyStore() {
239 libmupdf._wasm_empty_store()
240 }
241
242 export function shrinkStore(percent: number): boolean {
243 return libmupdf._wasm_shrink_store(percent)
244 }
245
246 export function installLoadFontFunction(f: (name: string, script: string, bold: boolean, italic: boolean) => Font | null) {
247 $libmupdf_load_font_file_js = f
248 }
249
250 /* -------------------------------------------------------------------------- */
251
252 // To pass Rect and Matrix as pointer arguments
253 const _wasm_int = Malloc<"int">(4)
254 const _wasm_point = Malloc<"fz_point">(4 * 6) >> 2
255 const _wasm_rect = Malloc<"fz_rect">(4 * 8) >> 2
256 const _wasm_matrix = Malloc<"fz_matrix">(4 * 6) >> 2
257 const _wasm_color = Malloc<"number">(4 * 4) >> 2
258 const _wasm_quad = Malloc<"fz_quad">(4 * 8) >> 2
259 const _wasm_string: [ Pointer<"char">, Pointer<"char"> ] = [ 0 as Pointer<"char">, 0 as Pointer<"char"> ]
260
261 function checkType(value: any, type: any) {
262 if (typeof type === "string" && typeof value !== type)
263 throw new TypeError("expected " + type)
264 if (typeof type === "function" && !(value instanceof type))
265 throw new TypeError("expected " + type.name)
266 }
267
268 function checkPoint(value: any): asserts value is Point {
269 if (!Array.isArray(value) || value.length !== 2)
270 throw new TypeError("expected point")
271 }
272
273 function checkRect(value: any): asserts value is Rect {
274 if (!Array.isArray(value) || value.length !== 4)
275 throw new TypeError("expected rectangle")
276 }
277
278 function checkMatrix(value: any): asserts value is Matrix {
279 if (!Array.isArray(value) || value.length !== 6)
280 throw new TypeError("expected matrix")
281 }
282
283 function checkQuad(value: any): asserts value is Quad {
284 if (!Array.isArray(value) || value.length !== 8)
285 throw new TypeError("expected quad")
286 }
287
288 function checkColor(value: any): asserts value is Color {
289 if (!Array.isArray(value) || (value.length !== 1 && value.length !== 3 && value.length !== 4))
290 throw new TypeError("expected color array")
291 }
292
293 function checkAnnotColor(value: any): asserts value is AnnotColor {
294 if (!Array.isArray(value) || (value.length !== 0 && value.length !== 1 && value.length !== 3 && value.length !== 4))
295 throw new TypeError("expected color array")
296 }
297
298 /** The types that can be automatically converted into a Buffer object */
299 type AnyBuffer = Buffer | ArrayBuffer | Uint8Array | string
300
301 function BUFFER(input: AnyBuffer) {
302 if (input instanceof Buffer)
303 return input.pointer
304 if (input instanceof ArrayBuffer || input instanceof Uint8Array)
305 return new Buffer(input).pointer
306 if (typeof input === "string")
307 return new Buffer(input).pointer
308 throw new TypeError("expected buffer")
309 }
310
311 function ENUM<T>(value: T, list: readonly T[]): number {
312 if (typeof value === "number") {
313 if (value >= 0 && value < list.length)
314 return value
315 }
316 if (typeof value === "string") {
317 let idx = list.indexOf(value)
318 if (idx >= 0)
319 return idx
320 }
321 throw new TypeError(`invalid enum value ("${value}"; expected ${list.join(", ")})`)
322 }
323
324 function allocateUTF8(str: string) {
325 var size = libmupdf.lengthBytesUTF8(str) + 1
326 var pointer = Malloc<"XXX">(size) as unknown as Pointer<"char">
327 libmupdf.stringToUTF8(str, pointer, size)
328 return pointer
329 }
330
331 function STRING_N(s: string, i: number) {
332 if (_wasm_string[i]) {
333 Free(_wasm_string[i])
334 _wasm_string[i] = 0 as Pointer<"char">
335 }
336 return _wasm_string[i] = allocateUTF8(s)
337 }
338
339 function STRING(s: string) {
340 return STRING_N(s, 0)
341 }
342
343 function STRING2(s: string) {
344 return STRING_N(s, 1)
345 }
346
347 function STRING_OPT(s: string | null | undefined) {
348 return typeof s === "string" ? STRING_N(s, 0) : 0 as Pointer<"char">
349 }
350
351 function STRING2_OPT(s: string | null | undefined) {
352 return typeof s === "string" ? STRING_N(s, 1) : 0 as Pointer<"char">
353 }
354
355 function POINT(p: Point) {
356 libmupdf.HEAPF32[_wasm_point + 0] = p[0]
357 libmupdf.HEAPF32[_wasm_point + 1] = p[1]
358 return _wasm_point << 2 as Pointer<"fz_point">
359 }
360
361 function POINT2(p: Point) {
362 libmupdf.HEAPF32[_wasm_point + 2] = p[0]
363 libmupdf.HEAPF32[_wasm_point + 3] = p[1]
364 return (_wasm_point + 2) << 2 as Pointer<"fz_point">
365 }
366
367 function POINT3(p: Point) {
368 libmupdf.HEAPF32[_wasm_point + 4] = p[0]
369 libmupdf.HEAPF32[_wasm_point + 5] = p[1]
370 return (_wasm_point + 4) << 2 as Pointer<"fz_point">
371 }
372
373 function RECT(r: Rect) {
374 libmupdf.HEAPF32[_wasm_rect + 0] = r[0]
375 libmupdf.HEAPF32[_wasm_rect + 1] = r[1]
376 libmupdf.HEAPF32[_wasm_rect + 2] = r[2]
377 libmupdf.HEAPF32[_wasm_rect + 3] = r[3]
378 return _wasm_rect << 2 as Pointer<"fz_rect">
379 }
380
381 function RECT2(r: Rect) {
382 libmupdf.HEAPF32[_wasm_rect + 4] = r[0]
383 libmupdf.HEAPF32[_wasm_rect + 5] = r[1]
384 libmupdf.HEAPF32[_wasm_rect + 6] = r[2]
385 libmupdf.HEAPF32[_wasm_rect + 7] = r[3]
386 return (_wasm_rect + 4) << 2 as Pointer<"fz_rect">
387 }
388
389 function MATRIX(m: Matrix) {
390 libmupdf.HEAPF32[_wasm_matrix + 0] = m[0]
391 libmupdf.HEAPF32[_wasm_matrix + 1] = m[1]
392 libmupdf.HEAPF32[_wasm_matrix + 2] = m[2]
393 libmupdf.HEAPF32[_wasm_matrix + 3] = m[3]
394 libmupdf.HEAPF32[_wasm_matrix + 4] = m[4]
395 libmupdf.HEAPF32[_wasm_matrix + 5] = m[5]
396 return _wasm_matrix << 2 as Pointer<"fz_matrix">
397 }
398
399 function QUAD(q: Quad) {
400 libmupdf.HEAPF32[_wasm_quad + 0] = q[0]
401 libmupdf.HEAPF32[_wasm_quad + 1] = q[1]
402 libmupdf.HEAPF32[_wasm_quad + 2] = q[2]
403 libmupdf.HEAPF32[_wasm_quad + 3] = q[3]
404 libmupdf.HEAPF32[_wasm_quad + 4] = q[4]
405 libmupdf.HEAPF32[_wasm_quad + 5] = q[5]
406 libmupdf.HEAPF32[_wasm_quad + 6] = q[6]
407 libmupdf.HEAPF32[_wasm_quad + 7] = q[7]
408 return _wasm_quad << 2 as Pointer<"fz_quad">
409 }
410
411 function COLOR(c?: AnnotColor) {
412 if (typeof c !== "undefined") {
413 switch (c.length) {
414 case 0:
415 break
416 case 1:
417 libmupdf.HEAPF32[_wasm_color + 0] = c[0]
418 break
419 case 3:
420 libmupdf.HEAPF32[_wasm_color + 0] = c[0]
421 libmupdf.HEAPF32[_wasm_color + 1] = c[1]
422 libmupdf.HEAPF32[_wasm_color + 2] = c[2]
423 break
424 case 4:
425 libmupdf.HEAPF32[_wasm_color + 0] = c[0]
426 libmupdf.HEAPF32[_wasm_color + 1] = c[1]
427 libmupdf.HEAPF32[_wasm_color + 2] = c[2]
428 libmupdf.HEAPF32[_wasm_color + 3] = c[3]
429 break
430 }
431 }
432 return _wasm_color << 2 as Pointer<"float">
433 }
434
435 /* -------------------------------------------------------------------------- */
436
437 function fromColor(n: number): Color {
438 if (n === 1)
439 return [
440 libmupdf.HEAPF32[_wasm_color] as number
441 ]
442 if (n === 3)
443 return [
444 libmupdf.HEAPF32[_wasm_color + 0] as number,
445 libmupdf.HEAPF32[_wasm_color + 1] as number,
446 libmupdf.HEAPF32[_wasm_color + 2] as number,
447 ]
448 if (n === 4)
449 return [
450 libmupdf.HEAPF32[_wasm_color + 0] as number,
451 libmupdf.HEAPF32[_wasm_color + 1] as number,
452 libmupdf.HEAPF32[_wasm_color + 2] as number,
453 libmupdf.HEAPF32[_wasm_color + 3] as number,
454 ]
455 throw new TypeError("invalid number of components for Color: " + n)
456 }
457
458 function fromAnnotColor(n: number): AnnotColor {
459 if (n === 0)
460 return []
461 return fromColor(n)
462 }
463
464 function fromColorArray(n: number, ptr: Pointer<"float">): number[] {
465 let addr = ptr >> 2
466 let color: number[] = []
467 for (let i = 0; i < n; ++i)
468 color.push(libmupdf.HEAPF32[addr + i] as number)
469 return color
470 }
471
472 function fromStringOrNull(ptr: Pointer<"char">): string | null {
473 if (ptr === 0)
474 return null
475 return libmupdf.UTF8ToString(ptr)
476 }
477
478 function fromString(ptr: Pointer<"char">): string {
479 return libmupdf.UTF8ToString(ptr)
480 }
481
482 function fromStringFree(ptr: Pointer<"char">): string {
483 let str = libmupdf.UTF8ToString(ptr)
484 Free(ptr)
485 return str
486 }
487
488 function fromPoint(ptr: Pointer<"fz_point">): Point {
489 let addr = ptr >> 2
490 return [
491 libmupdf.HEAPF32[addr + 0] as number,
492 libmupdf.HEAPF32[addr + 1] as number,
493 ]
494 }
495
496 function fromRect(ptr: Pointer<"fz_rect">): Rect {
497 let addr = ptr >> 2
498 return [
499 libmupdf.HEAPF32[addr + 0] as number,
500 libmupdf.HEAPF32[addr + 1] as number,
501 libmupdf.HEAPF32[addr + 2] as number,
502 libmupdf.HEAPF32[addr + 3] as number,
503 ]
504 }
505
506 function fromMatrix(ptr: Pointer<"fz_matrix">): Matrix {
507 let addr = ptr >> 2
508 return [
509 libmupdf.HEAPF32[addr + 0] as number,
510 libmupdf.HEAPF32[addr + 1] as number,
511 libmupdf.HEAPF32[addr + 2] as number,
512 libmupdf.HEAPF32[addr + 3] as number,
513 libmupdf.HEAPF32[addr + 4] as number,
514 libmupdf.HEAPF32[addr + 5] as number,
515 ]
516 }
517
518 function fromQuad(ptr: Pointer<"fz_quad">): Quad {
519 let addr = ptr >> 2
520 return [
521 libmupdf.HEAPF32[addr + 0] as number,
522 libmupdf.HEAPF32[addr + 1] as number,
523 libmupdf.HEAPF32[addr + 2] as number,
524 libmupdf.HEAPF32[addr + 3] as number,
525 libmupdf.HEAPF32[addr + 4] as number,
526 libmupdf.HEAPF32[addr + 5] as number,
527 libmupdf.HEAPF32[addr + 6] as number,
528 libmupdf.HEAPF32[addr + 7] as number,
529 ]
530 }
531
532 function fromBuffer(ptr: Pointer<"fz_buffer">): Uint8Array {
533 let data = libmupdf._wasm_buffer_get_data(ptr)
534 let size = libmupdf._wasm_buffer_get_len(ptr)
535 return libmupdf.HEAPU8.slice(data, data + size)
536 }
537
538 function fromLayerConfigUIInfo(ptr: Pointer<"pdf_layer_config_ui">): Object {
539 return {
540 text: libmupdf._wasm_pdf_layer_config_ui_get_text(ptr),
541 depth: libmupdf._wasm_pdf_layer_config_ui_get_depth(ptr),
542 type: libmupdf._wasm_pdf_layer_config_ui_get_type(ptr),
543 selected: libmupdf._wasm_pdf_layer_config_ui_get_selected(ptr),
544 locked: libmupdf._wasm_pdf_layer_config_ui_get_locked(ptr),
545 }
546 }
547
548 /* unused for now
549 function rgbFromColor(c?: Color): [number, number, number] {
550 var r = 0, g = 0, b = 0
551 if (typeof c !== "undefined") {
552 switch (c.length) {
553 case 1:
554 r = g = b = c[0]
555 break
556 case 3:
557 r = c[0]
558 g = c[1]
559 b = c[2]
560 break
561 case 4:
562 r = 1 - Math.min(1, c[0] + c[3])
563 g = 1 - Math.min(1, c[1] + c[3])
564 b = 1 - Math.min(1, c[2] + c[3])
565 break
566 }
567 }
568 return [ r, g, b ]
569 }
570
571 function numberFromColor(c?: Color): number {
572 var [ r, g, b ] = rgbFromColor(c)
573 return (255 << 24) | (r << 16) | (g << 8) | b
574 }
575 */
576
577 function colorFromNumber(argb: number): Color {
578 var r = (argb >> 16) & 255
579 var g = (argb >> 8) & 255
580 var b = (argb) & 255
581 return [ r / 255, g / 255, b / 255 ]
582 }
583
584 /* -------------------------------------------------------------------------- */
585
586 type SearchFunction = (
587 display_list: any,
588 needle: Pointer<"char">,
589 marks: Pointer<"int">,
590 hits: Pointer<"fz_quad">,
591 hit_max: number
592 ) => number
593
594 function runSearch(searchFun: SearchFunction, searchThis: number, needle: string, max_hits = 500) {
595 checkType(needle, "string")
596 let hits = 0 as Pointer<"fz_quad">
597 let marks = 0 as Pointer<"int">
598 try {
599 hits = Malloc<"fz_quad">(32 * max_hits)
600 marks = Malloc<"int">(4 * max_hits)
601 let n = searchFun(searchThis as any, STRING(needle), marks, hits, max_hits)
602 let outer: Quad[][] = []
603 if (n > 0) {
604 let inner: Quad[] = []
605 for (let i = 0; i < n; ++i) {
606 let mark = libmupdf.HEAP32[(marks>>2) + i]
607 let quad = fromQuad(hits + i * 32 as Pointer<"fz_quad">)
608 if (i > 0 && mark) {
609 outer.push(inner)
610 inner = []
611 }
612 inner.push(quad)
613 }
614 outer.push(inner)
615 }
616 return outer
617 } finally {
618 Free(marks)
619 Free(hits)
620 }
621 }
622
623 /* -------------------------------------------------------------------------- */
624
625 abstract class Userdata<B> {
626 private static _finalizer: FinalizationRegistry<number>
627
628 static readonly _drop: (pointer: any) => void
629
630 pointer: Pointer<B>
631
632 constructor(pointer: Pointer<B>) {
633 if (typeof pointer !== "number")
634 throw new Error("invalid pointer: " + typeof pointer)
635 if (pointer !== 0) {
636 let ctor = this.constructor as typeof Userdata
637 if (!ctor._finalizer)
638 ctor._finalizer = new FinalizationRegistry(ctor._drop)
639 ctor._finalizer.register(this, pointer, this)
640 }
641 this.pointer = pointer
642 }
643
644 destroy() {
645 if (this.pointer !== 0) {
646 let ctor = this.constructor as typeof Userdata
647 ctor._finalizer.unregister(this)
648 ctor._drop(this.pointer)
649 }
650 this.pointer = 0 as Pointer<B>
651 }
652
653 // Custom "console.log" formatting for Node
654 [Symbol.for("nodejs.util.inspect.custom")]() {
655 return this.toString()
656 }
657
658 toString() {
659 return `[${this.constructor.name} ${this.pointer}]`
660 }
661
662 valueOf() {
663 throw new Error("cannot convert Userdata to Javascript value")
664 }
665 }
666
667 export class Buffer extends Userdata<"fz_buffer"> {
668 static override readonly _drop = libmupdf._wasm_drop_buffer
669
670 /** New empty Buffer. */
671 constructor()
672
673 /** New Buffer initialized with string contents as UTF-8. */
674 constructor(data: string)
675
676 /** New Buffer initialized with typed array contents. */
677 constructor(data: ArrayBuffer | Uint8Array)
678
679 /** PRIVATE */
680 constructor(pointer: Pointer<"fz_buffer">)
681
682 constructor(arg?: Pointer<"fz_buffer"> | string | ArrayBuffer | Uint8Array) {
683 if (typeof arg === "undefined")
684 super(libmupdf._wasm_new_buffer(1024))
685
686 else if (typeof arg === "number")
687 super(arg)
688
689 else if (typeof arg === "string") {
690 let data_len = libmupdf.lengthBytesUTF8(arg)
691 let data_ptr = Malloc<"char">(data_len + 1)
692 libmupdf.stringToUTF8(arg, data_ptr, data_len + 1)
693 super(libmupdf._wasm_new_buffer_from_data(data_ptr, data_len))
694 }
695
696 else if (arg instanceof ArrayBuffer || arg instanceof Uint8Array) {
697 let data_len = arg.byteLength
698 let data_ptr = Malloc<"char">(data_len)
699 libmupdf.HEAPU8.set(new Uint8Array(arg), data_ptr)
700 super(libmupdf._wasm_new_buffer_from_data(data_ptr, data_len))
701 }
702 }
703
704 get length() {
705 return this.getLength()
706 }
707
708 set length(_: number) {
709 throw new TypeError("buffer length is read-only")
710 }
711
712 getLength() {
713 return libmupdf._wasm_buffer_get_len(this.pointer)
714 }
715
716 readByte(at: number) {
717 let data = libmupdf._wasm_buffer_get_data(this.pointer)
718 return libmupdf.HEAPU8[data + at] as number
719 }
720
721 write(s: string) {
722 libmupdf._wasm_append_string(this.pointer, STRING(s))
723 }
724
725 writeByte(b: number) {
726 libmupdf._wasm_append_byte(this.pointer, b)
727 }
728
729 writeLine(s: string) {
730 this.write(s)
731 this.writeByte(10)
732 }
733
734 writeBuffer(other: AnyBuffer) {
735 libmupdf._wasm_append_buffer(this.pointer, BUFFER(other))
736 }
737
738 asUint8Array() {
739 let data = libmupdf._wasm_buffer_get_data(this.pointer)
740 let size = libmupdf._wasm_buffer_get_len(this.pointer)
741 return libmupdf.HEAPU8.subarray(data, data + size)
742 }
743
744 slice(start: number, end?: number) {
745 if (typeof end === "undefined")
746 end = this.getLength()
747 return new Buffer(libmupdf._wasm_slice_buffer(this.pointer, start, end))
748 }
749
750 asString() {
751 return fromString(libmupdf._wasm_string_from_buffer(this.pointer))
752 }
753
754 save(filename: string) {
755 if (node_fs)
756 node_fs.writeFileSync(filename, this.asUint8Array())
757 else
758 throw new Error("missing 'fs' module")
759 }
760 }
761
762 export type ColorSpaceType =
763 "None" |
764 "Gray" |
765 "RGB" |
766 "BGR" |
767 "CMYK" |
768 "Lab" |
769 "Indexed" |
770 "Separation"
771
772 export class ColorSpace extends Userdata<"fz_colorspace"> {
773 static override readonly _drop = libmupdf._wasm_drop_colorspace
774
775 static readonly COLORSPACE_TYPES: ColorSpaceType[] = [
776 "None",
777 "Gray",
778 "RGB",
779 "BGR",
780 "CMYK",
781 "Lab",
782 "Indexed",
783 "Separation"
784 ]
785
786 // Create ColorSpace from ICC profile.
787 constructor(profile: AnyBuffer, name: string)
788
789 // PRIVATE
790 constructor(pointer: Pointer<"fz_colorspace">)
791
792 constructor(from: Pointer<"fz_colorspace"> | AnyBuffer, name?: string) {
793 if (typeof from === "number") {
794 super(from)
795 } else {
796 if (typeof from === "string") {
797 if (node_fs)
798 from = node_fs.readFileSync(from)
799 else
800 throw new Error("missing 'fs' module")
801 }
802 super(libmupdf._wasm_new_icc_colorspace(STRING_OPT(name), BUFFER(from as AnyBuffer)))
803 }
804 }
805
806 getName() {
807 return fromString(libmupdf._wasm_colorspace_get_name(this.pointer))
808 }
809
810 getType() {
811 return ColorSpace.COLORSPACE_TYPES[libmupdf._wasm_colorspace_get_type(this.pointer)] || "None"
812 }
813
814 getNumberOfComponents() {
815 return libmupdf._wasm_colorspace_get_n(this.pointer)
816 }
817
818 isGray(): boolean { return this.getType() === "Gray" }
819 isRGB(): boolean { return this.getType() === "RGB" }
820 isCMYK(): boolean { return this.getType() === "CMYK" }
821 isIndexed(): boolean { return this.getType() === "Indexed" }
822 isLab(): boolean { return this.getType() === "Lab" }
823 isDeviceN(): boolean { return this.getType() === "Separation" }
824 isSubtractive(): boolean { return this.getType() === "CMYK" || this.getType() === "Separation" }
825
826 override toString() {
827 return "[ColorSpace " + this.getName() + "]"
828 }
829
830 static readonly DeviceGray = new ColorSpace(libmupdf._wasm_device_gray())
831 static readonly DeviceRGB = new ColorSpace(libmupdf._wasm_device_rgb())
832 static readonly DeviceBGR = new ColorSpace(libmupdf._wasm_device_bgr())
833 static readonly DeviceCMYK = new ColorSpace(libmupdf._wasm_device_cmyk())
834 static readonly Lab = new ColorSpace(libmupdf._wasm_device_lab())
835 }
836
837 export type FontSimpleEncoding = "Latin" | "Greek" | "Cyrillic"
838
839 export type FontCJKOrdering = 0 | 1 | 2 | 3
840
841 export type FontCJKLanguage =
842 "Adobe-CNS1" |
843 "Adobe-GB1" |
844 "Adobe-Japan1" |
845 "Adobe-Korea1" |
846 "zh-Hant" |
847 "zh-TW" |
848 "zh-HK" |
849 "zh-Hans" |
850 "zh-CN" |
851 "ja" |
852 "ko"
853
854 export class Font extends Userdata<"fz_font"> {
855 static override readonly _drop = libmupdf._wasm_drop_font
856
857 static readonly SIMPLE_ENCODING: FontSimpleEncoding[] = [
858 "Latin",
859 "Greek",
860 "Cyrillic"
861 ]
862
863 static readonly SIMPLE_ENCODING_LATIN = "Latin"
864 static readonly SIMPLE_ENCODING_GREEK = "Greek"
865 static readonly SIMPLE_ENCODING_CYRILLIC = "Cyrillic"
866
867 static readonly ADOBE_CNS = 0
868 static readonly ADOBE_GB = 1
869 static readonly ADOBE_JAPAN = 2
870 static readonly ADOBE_KOREA = 3
871
872 static readonly CJK_ORDERING_BY_LANG: Record<FontCJKLanguage,FontCJKOrdering> = {
873 "Adobe-CNS1": 0,
874 "Adobe-GB1": 1,
875 "Adobe-Japan1": 2,
876 "Adobe-Korea1": 3,
877 "zh-Hant": 0,
878 "zh-TW": 0,
879 "zh-HK": 0,
880 "zh-Hans": 1,
881 "zh-CN": 1,
882 "ja": 2,
883 "ko": 3,
884 }
885
886 constructor(name: string)
887 constructor(name: string, filename: string, subfont?: number)
888 constructor(name: string, data: AnyBuffer, subfont?: number)
889 constructor(pointer: Pointer<"fz_font">)
890
891 constructor(name_or_pointer: Pointer<"fz_font"> | string, data?: AnyBuffer, subfont=0) {
892 let pointer = 0 as Pointer<"fz_font">
893 if (typeof name_or_pointer === "number") {
894 pointer = libmupdf._wasm_keep_font(name_or_pointer)
895 } else {
896 if (typeof data === "string") {
897 if (node_fs)
898 data = node_fs.readFileSync(data)
899 else
900 throw new Error("missing 'fs' module")
901 }
902 if (data)
903 pointer = libmupdf._wasm_new_font_from_buffer(STRING(name_or_pointer), BUFFER(data), subfont)
904 else if (name_or_pointer === "zh-Hant")
905 pointer = libmupdf._wasm_new_cjk_font(Font.ADOBE_CNS)
906 else if (name_or_pointer === "zh-Hans")
907 pointer = libmupdf._wasm_new_cjk_font(Font.ADOBE_GB)
908 else if (name_or_pointer === "ja")
909 pointer = libmupdf._wasm_new_cjk_font(Font.ADOBE_JAPAN)
910 else if (name_or_pointer === "ko")
911 pointer = libmupdf._wasm_new_cjk_font(Font.ADOBE_KOREA)
912 else
913 pointer = libmupdf._wasm_new_base14_font(STRING(name_or_pointer))
914 }
915 super(pointer)
916 }
917
918 getName() {
919 return fromString(libmupdf._wasm_font_get_name(this.pointer))
920 }
921
922 encodeCharacter(uni: number | string) {
923 if (typeof uni === "string")
924 uni = uni.charCodeAt(0)
925 return libmupdf._wasm_encode_character(this.pointer, uni)
926 }
927
928 advanceGlyph(gid: number, wmode = 0) {
929 return libmupdf._wasm_advance_glyph(this.pointer, gid, wmode)
930 }
931
932 isMono() {
933 return !!libmupdf._wasm_font_is_monospaced(this.pointer)
934 }
935
936 isSerif() {
937 return !!libmupdf._wasm_font_is_serif(this.pointer)
938 }
939
940 isBold() {
941 return !!libmupdf._wasm_font_is_bold(this.pointer)
942 }
943
944 isItalic() {
945 return !!libmupdf._wasm_font_is_italic(this.pointer)
946 }
947 }
948
949 export class Image extends Userdata<"fz_image"> {
950 static override readonly _drop = libmupdf._wasm_drop_image
951
952 constructor(pointer: Pointer<"fz_image">)
953 constructor(filename: string)
954 constructor(data: AnyBuffer)
955 constructor(pixmap: Pixmap, mask?: Image)
956
957 constructor(data: Pointer<"fz_image"> | Pixmap | AnyBuffer, mask?: Image) {
958 let pointer = 0 as Pointer<"fz_image">
959 if (typeof data === "number") {
960 pointer = libmupdf._wasm_keep_image(data)
961 } else if (data instanceof Pixmap) {
962 pointer = libmupdf._wasm_new_image_from_pixmap(
963 data.pointer,
964 mask ? mask.pointer : 0 as Pointer<"fz_image">
965 )
966 } else {
967 if (typeof data === "string") {
968 if (node_fs)
969 data = node_fs.readFileSync(data)
970 else
971 throw new Error("missing 'fs' module")
972 }
973 pointer = libmupdf._wasm_new_image_from_buffer(BUFFER(data as Uint8Array))
974 }
975 super(pointer)
976 }
977
978 getWidth() {
979 return libmupdf._wasm_image_get_w(this.pointer)
980 }
981
982 getHeight() {
983 return libmupdf._wasm_image_get_h(this.pointer)
984 }
985
986 getNumberOfComponents() {
987 return libmupdf._wasm_image_get_n(this.pointer)
988 }
989
990 getBitsPerComponent() {
991 return libmupdf._wasm_image_get_bpc(this.pointer)
992 }
993
994 getXResolution() {
995 return libmupdf._wasm_image_get_xres(this.pointer)
996 }
997
998 getYResolution() {
999 return libmupdf._wasm_image_get_yres(this.pointer)
1000 }
1001
1002 getImageMask() {
1003 return !!libmupdf._wasm_image_get_imagemask(this.pointer)
1004 }
1005
1006 getColorSpace() {
1007 let cs = libmupdf._wasm_image_get_colorspace(this.pointer)
1008 if (cs)
1009 return new ColorSpace(libmupdf._wasm_keep_colorspace(cs))
1010 return null
1011 }
1012
1013 getMask() {
1014 let mask = libmupdf._wasm_image_get_mask(this.pointer)
1015 if (mask)
1016 return new Image(libmupdf._wasm_keep_image(mask))
1017 return null
1018 }
1019
1020 toPixmap() {
1021 return new Pixmap(libmupdf._wasm_get_pixmap_from_image(this.pointer))
1022 }
1023 }
1024
1025 export type LineCap = "Butt" | "Round" | "Square" | "Triangle"
1026 export type LineJoin = "Miter" | "Round" | "Bevel" | "MiterXPS"
1027
1028 // TODO: convert StrokeState from plain JS object to match mutool run ffi_pushstroke/ffi_tostroke
1029
1030 export type StrokeStateData = {
1031 lineCap: LineCap,
1032 lineJoin: LineJoin,
1033 lineWidth: number,
1034 miterLimit: number,
1035 dashPhase?: number,
1036 dashes?: number[],
1037 }
1038
1039 export class StrokeState extends Userdata<"fz_stroke_state"> {
1040 static override readonly _drop = libmupdf._wasm_drop_stroke_state
1041
1042 static readonly LINE_CAP: LineCap[] = [
1043 "Butt",
1044 "Round",
1045 "Square",
1046 "Triangle"
1047 ]
1048
1049 static readonly LINE_JOIN: LineJoin[] = [
1050 "Miter",
1051 "Round",
1052 "Bevel",
1053 "MiterXPS"
1054 ]
1055
1056 constructor(data: Pointer<"fz_stroke_state"> | StrokeStateData) {
1057 if (typeof data === "number") {
1058 super(data)
1059 return this
1060 }
1061 super(libmupdf._wasm_new_stroke_state(data?.dashes?.length ?? 0))
1062 let lineCap = ENUM<LineCap>(data.lineCap, StrokeState.LINE_CAP)
1063 let lineJoin = ENUM<LineJoin>(data.lineJoin, StrokeState.LINE_JOIN)
1064 libmupdf._wasm_stroke_state_set_start_cap(this.pointer, lineCap)
1065 libmupdf._wasm_stroke_state_set_dash_cap(this.pointer, lineCap)
1066 libmupdf._wasm_stroke_state_set_end_cap(this.pointer, lineCap)
1067 libmupdf._wasm_stroke_state_set_linejoin(this.pointer, lineJoin)
1068 libmupdf._wasm_stroke_state_set_linewidth(this.pointer, data.lineWidth)
1069 libmupdf._wasm_stroke_state_set_miterlimit(this.pointer, data.miterLimit)
1070 libmupdf._wasm_stroke_state_set_dash_phase(this.pointer, data.dashPhase ?? 0)
1071 if (data.dashes) {
1072 for (let i = 0; i < data.dashes.length; ++i)
1073 libmupdf._wasm_stroke_state_set_dash_item(this.pointer, i, data.dashes[i] ?? 0)
1074 }
1075 }
1076
1077 getLineCap() {
1078 return libmupdf._wasm_stroke_state_get_start_cap(this.pointer)
1079 }
1080
1081 getLineJoin() {
1082 return libmupdf._wasm_stroke_state_get_linejoin(this.pointer)
1083 }
1084
1085 getLineWidth() {
1086 return libmupdf._wasm_stroke_state_get_linewidth(this.pointer)
1087 }
1088
1089 getMiterLimit() {
1090 return libmupdf._wasm_stroke_state_get_miterlimit(this.pointer)
1091 }
1092
1093 getDashPhase() {
1094 return libmupdf._wasm_stroke_state_get_dash_phase(this.pointer)
1095 }
1096
1097 getDashes(): number[] | null {
1098 var n = libmupdf._wasm_stroke_state_get_dash_len(this.pointer)
1099 if (n > 0) {
1100 var out: number[] = []
1101 for (let i = 0; i < n; ++i)
1102 out[i] = libmupdf._wasm_stroke_state_get_dash_item(this.pointer, i)
1103 return out
1104 }
1105 return null
1106 }
1107 }
1108
1109 interface PathWalker {
1110 moveTo?(x: number, y: number): void
1111 lineTo?(x: number, y: number): void
1112 curveTo?(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): void
1113 closePath?(): void
1114 }
1115
1116 export class Path extends Userdata<"fz_path"> {
1117 static override readonly _drop = libmupdf._wasm_drop_path
1118
1119 constructor(pointer?: Pointer<"fz_path">) {
1120 if (typeof pointer === "number")
1121 super(pointer)
1122 else
1123 super(libmupdf._wasm_new_path())
1124 }
1125
1126 getBounds(strokeState: StrokeState, transform: Matrix) {
1127 if (strokeState !== null)
1128 checkType(strokeState, StrokeState)
1129 checkMatrix(transform)
1130 return fromRect(libmupdf._wasm_bound_path(this.pointer, strokeState?.pointer, MATRIX(transform)))
1131 }
1132
1133 moveTo(x: number, y: number) {
1134 checkType(x, "number")
1135 checkType(y, "number")
1136 libmupdf._wasm_moveto(this.pointer, x, y)
1137 }
1138
1139 lineTo(x: number, y: number) {
1140 checkType(x, "number")
1141 checkType(y, "number")
1142 libmupdf._wasm_lineto(this.pointer, x, y)
1143 }
1144
1145 curveTo(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number) {
1146 checkType(x1, "number")
1147 checkType(y1, "number")
1148 checkType(x2, "number")
1149 checkType(y2, "number")
1150 checkType(x3, "number")
1151 checkType(y3, "number")
1152 libmupdf._wasm_curveto(this.pointer, x1, y1, x2, y2, x3, y3)
1153 }
1154
1155 curveToV(cx: number, cy: number, ex: number, ey: number) {
1156 checkType(cx, "number")
1157 checkType(cy, "number")
1158 checkType(ex, "number")
1159 checkType(ey, "number")
1160 libmupdf._wasm_curvetov(this.pointer, cx, cy, ex, ey)
1161 }
1162
1163 curveToY(cx: number, cy: number, ex: number, ey: number) {
1164 checkType(cx, "number")
1165 checkType(cy, "number")
1166 checkType(ex, "number")
1167 checkType(ey, "number")
1168 libmupdf._wasm_curvetoy(this.pointer, cx, cy, ex, ey)
1169 }
1170
1171 closePath() {
1172 libmupdf._wasm_closepath(this.pointer)
1173 }
1174
1175 rect(x1: number, y1: number, x2: number, y2: number) {
1176 checkType(x1, "number")
1177 checkType(y1, "number")
1178 checkType(x2, "number")
1179 checkType(y2, "number")
1180 libmupdf._wasm_rectto(this.pointer, x1, y1, x2, y2)
1181 }
1182
1183 transform(matrix: Matrix) {
1184 checkMatrix(matrix)
1185 libmupdf._wasm_transform_path(this.pointer, MATRIX(matrix))
1186 }
1187
1188 walk(walker: PathWalker) {
1189 let id = $libmupdf_path_id++
1190 $libmupdf_path_table.set(id, walker)
1191 libmupdf._wasm_walk_path(this.pointer, id)
1192 $libmupdf_path_table.delete(id)
1193 }
1194 }
1195
1196 interface TextWalker {
1197 beginSpan?(font: Font, trm: Matrix, wmode: number, bidi: number, markupDirection: number, language: string): void
1198 showGlyph?(font: Font, trm: Matrix, glyph: number, unicode: number, wmode: number, bidi: number): void
1199 endSpan?(): void
1200 }
1201
1202 export class Text extends Userdata<"fz_text"> {
1203 static override readonly _drop = libmupdf._wasm_drop_text
1204
1205 constructor(pointer?: Pointer<"fz_text">) {
1206 if (typeof pointer === "number")
1207 super(pointer)
1208 else
1209 super(libmupdf._wasm_new_text())
1210 }
1211
1212 getBounds(strokeState: StrokeState, transform: Matrix) {
1213 if (strokeState !== null)
1214 checkType(strokeState, StrokeState)
1215 checkMatrix(transform)
1216 return fromRect(libmupdf._wasm_bound_text(this.pointer, strokeState?.pointer, MATRIX(transform)))
1217 }
1218
1219 showGlyph(font: Font, trm: Matrix, gid: number, uni: number, wmode = 0) {
1220 checkType(font, Font)
1221 checkMatrix(trm)
1222 checkType(gid, "number")
1223 checkType(uni, "number")
1224 libmupdf._wasm_show_glyph(
1225 this.pointer,
1226 font.pointer,
1227 MATRIX(trm),
1228 gid,
1229 uni,
1230 wmode
1231 )
1232 }
1233
1234 showString(font: Font, trm: Matrix, str: string, wmode = 0) {
1235 checkType(font, Font)
1236 checkMatrix(trm)
1237 checkType(str, "string")
1238 return fromMatrix(
1239 libmupdf._wasm_show_string(
1240 this.pointer,
1241 font.pointer,
1242 MATRIX(trm),
1243 STRING(str),
1244 wmode
1245 )
1246 )
1247 }
1248
1249 walk(walker: TextWalker) {
1250 let id = $libmupdf_text_id++
1251 $libmupdf_text_table.set(id, walker)
1252 libmupdf._wasm_walk_text(this.pointer, id)
1253 $libmupdf_text_table.delete(id)
1254 }
1255 }
1256
1257 export class DisplayList extends Userdata<"fz_display_list"> {
1258 static override readonly _drop = libmupdf._wasm_drop_display_list
1259
1260 constructor(pointer: Pointer<"fz_display_list">)
1261 constructor(mediabox: Rect)
1262
1263 constructor(arg1: Pointer<"fz_display_list"> | Rect) {
1264 let pointer = 0 as Pointer<"fz_display_list">
1265 if (typeof arg1 === "number") {
1266 pointer = arg1
1267 } else {
1268 checkRect(arg1)
1269 pointer = libmupdf._wasm_new_display_list(RECT(arg1))
1270 }
1271 super(pointer)
1272 }
1273
1274 getBounds() {
1275 return fromRect(libmupdf._wasm_bound_display_list(this.pointer))
1276 }
1277
1278 toPixmap(matrix: Matrix, colorspace: ColorSpace, alpha = false) {
1279 checkMatrix(matrix)
1280 checkType(colorspace, ColorSpace)
1281 return new Pixmap(
1282 libmupdf._wasm_new_pixmap_from_display_list(
1283 this.pointer,
1284 MATRIX(matrix),
1285 colorspace.pointer,
1286 alpha
1287 )
1288 )
1289 }
1290
1291 toStructuredText(options = "") {
1292 checkType(options, "string")
1293 return new StructuredText(libmupdf._wasm_new_stext_page_from_display_list(this.pointer, STRING(options)))
1294 }
1295
1296 run(device: Device, matrix: Matrix) {
1297 checkType(device, Device)
1298 checkMatrix(matrix)
1299 libmupdf._wasm_run_display_list(this.pointer, device.pointer, MATRIX(matrix))
1300 }
1301
1302 search(needle: string, max_hits = 500) {
1303 return runSearch(libmupdf._wasm_search_display_list, this.pointer, needle, max_hits)
1304 }
1305 }
1306
1307 export class Pixmap extends Userdata<"fz_pixmap"> {
1308 static override readonly _drop = libmupdf._wasm_drop_pixmap
1309
1310 constructor(pointer: Pointer<"fz_pixmap">)
1311 constructor(colorspace: ColorSpace, bbox: Rect, alpha: boolean)
1312
1313 constructor(arg1: Pointer<"fz_pixmap"> | ColorSpace, bbox?: Rect, alpha = false) {
1314 if (typeof arg1 === "number") {
1315 super(arg1)
1316 }
1317 if (arg1 instanceof ColorSpace) {
1318 checkRect(bbox)
1319 super(libmupdf._wasm_new_pixmap_with_bbox(arg1.pointer, RECT(bbox), alpha))
1320 }
1321 if (arg1 === null) {
1322 checkRect(bbox)
1323 super(libmupdf._wasm_new_pixmap_with_bbox(0 as Pointer<"fz_colorspace">, RECT(bbox), alpha))
1324 }
1325 }
1326
1327 getBounds() {
1328 let x = libmupdf._wasm_pixmap_get_x(this.pointer)
1329 let y = libmupdf._wasm_pixmap_get_y(this.pointer)
1330 let w = libmupdf._wasm_pixmap_get_w(this.pointer)
1331 let h = libmupdf._wasm_pixmap_get_h(this.pointer)
1332 return [ x, y, x + w, y + h ]
1333 }
1334
1335 clear(value?: number) {
1336 if (typeof value === "undefined")
1337 libmupdf._wasm_clear_pixmap(this.pointer)
1338 else
1339 libmupdf._wasm_clear_pixmap_with_value(this.pointer, value)
1340 }
1341
1342 getWidth() {
1343 return libmupdf._wasm_pixmap_get_w(this.pointer)
1344 }
1345 getHeight() {
1346 return libmupdf._wasm_pixmap_get_h(this.pointer)
1347 }
1348 getX() {
1349 return libmupdf._wasm_pixmap_get_x(this.pointer)
1350 }
1351 getY() {
1352 return libmupdf._wasm_pixmap_get_y(this.pointer)
1353 }
1354 getStride() {
1355 return libmupdf._wasm_pixmap_get_stride(this.pointer)
1356 }
1357 getNumberOfComponents() {
1358 return libmupdf._wasm_pixmap_get_n(this.pointer)
1359 }
1360 getAlpha() {
1361 return libmupdf._wasm_pixmap_get_alpha(this.pointer)
1362 }
1363 getXResolution() {
1364 return libmupdf._wasm_pixmap_get_xres(this.pointer)
1365 }
1366 getYResolution() {
1367 return libmupdf._wasm_pixmap_get_yres(this.pointer)
1368 }
1369
1370 setResolution(x: number, y: number) {
1371 libmupdf._wasm_pixmap_set_xres(this.pointer, x)
1372 libmupdf._wasm_pixmap_set_yres(this.pointer, y)
1373 }
1374
1375 getColorSpace() {
1376 let cs = libmupdf._wasm_pixmap_get_colorspace(this.pointer)
1377 if (cs)
1378 return new ColorSpace(libmupdf._wasm_keep_colorspace(cs))
1379 return null
1380 }
1381
1382 getPixels() {
1383 let s = libmupdf._wasm_pixmap_get_stride(this.pointer)
1384 let h = libmupdf._wasm_pixmap_get_h(this.pointer)
1385 let p = libmupdf._wasm_pixmap_get_samples(this.pointer)
1386 return new Uint8ClampedArray(libmupdf.HEAPU8.buffer, p, s * h)
1387 }
1388
1389 asPNG() {
1390 let buf = libmupdf._wasm_new_buffer_from_pixmap_as_png(this.pointer)
1391 try {
1392 return fromBuffer(buf)
1393 } finally {
1394 libmupdf._wasm_drop_buffer(buf)
1395 }
1396 }
1397
1398 asPSD() {
1399 let buf = libmupdf._wasm_new_buffer_from_pixmap_as_psd(this.pointer)
1400 try {
1401 return fromBuffer(buf)
1402 } finally {
1403 libmupdf._wasm_drop_buffer(buf)
1404 }
1405 }
1406
1407 asPAM() {
1408 let buf = libmupdf._wasm_new_buffer_from_pixmap_as_pam(this.pointer)
1409 try {
1410 return fromBuffer(buf)
1411 } finally {
1412 libmupdf._wasm_drop_buffer(buf)
1413 }
1414 }
1415
1416 asJPEG(quality: number, invert_cmyk=false) {
1417 let buf = libmupdf._wasm_new_buffer_from_pixmap_as_jpeg(this.pointer, quality, invert_cmyk)
1418 try {
1419 return fromBuffer(buf)
1420 } finally {
1421 libmupdf._wasm_drop_buffer(buf)
1422 }
1423 }
1424
1425 invert() {
1426 libmupdf._wasm_invert_pixmap(this.pointer)
1427 }
1428
1429 invertLuminance() {
1430 libmupdf._wasm_invert_pixmap_luminance(this.pointer)
1431 }
1432
1433 gamma(p: number) {
1434 libmupdf._wasm_gamma_pixmap(this.pointer, p)
1435 }
1436
1437 tint(black: number | Color, white: number | Color) {
1438 let black_hex = 0x000000
1439 let white_hex = 0xffffff
1440 if (typeof black === "number")
1441 black_hex = black
1442 else if (black instanceof Array && black.length === 3)
1443 black_hex = ( ( (black[0] * 255) << 16 ) | ( (black[1] * 255) << 8 ) | ( (black[2] * 255) ) )
1444 if (typeof white === "number")
1445 white_hex = white
1446 else if (white instanceof Array && white.length === 3)
1447 white = ( ( (white[0] * 255) << 16 ) | ( (white[1] * 255) << 8 ) | ( (white[2] * 255) ) )
1448 libmupdf._wasm_tint_pixmap(this.pointer, black_hex, white_hex)
1449 }
1450
1451 convertToColorSpace(colorspace: ColorSpace, keepAlpha=false) {
1452 checkType(colorspace, ColorSpace)
1453 checkType(keepAlpha, "boolean")
1454 return new Pixmap(libmupdf._wasm_convert_pixmap(this.pointer, colorspace.pointer, keepAlpha))
1455 }
1456
1457 warp(points: Point[], width: number, height: number) {
1458 let quad = points.flat()
1459 checkQuad(quad)
1460 checkType(width, "number")
1461 checkType(height, "number")
1462 return new Pixmap(libmupdf._wasm_warp_pixmap(this.pointer, QUAD(quad), width, height))
1463 }
1464 }
1465
1466 export class Shade extends Userdata<"fz_shade"> {
1467 static override readonly _drop = libmupdf._wasm_drop_shade
1468 getBounds() {
1469 return fromRect(libmupdf._wasm_bound_shade(this.pointer))
1470 }
1471 }
1472
1473 interface StructuredTextWalker {
1474 onImageBlock?(bbox: Rect, transform: Matrix, image: Image): void
1475 beginTextBlock?(bbox: Rect): void
1476 beginLine?(bbox: Rect, wmode: number, direction: Point): void
1477 onChar?(c: string, origin: Point, font: Font, size: number, quad: Quad, color: Color): void
1478 endLine?(): void
1479 endTextBlock?(): void
1480 onVector?(bbox: Rect, flags: any, color: Color): void
1481 }
1482
1483 type SelectMode = "chars" | "words" | "lines"
1484
1485 export class StructuredText extends Userdata<"fz_stext_page"> {
1486 static override readonly _drop = libmupdf._wasm_drop_stext_page
1487
1488 static readonly SELECT_MODE: SelectMode[] = [
1489 "chars",
1490 "words",
1491 "lines"
1492 ]
1493
1494 static readonly SELECT_CHARS = "chars"
1495 static readonly SELECT_WORDS = "words"
1496 static readonly SELECT_LINES = "lines"
1497
1498 walk(walker: StructuredTextWalker) {
1499 let block = libmupdf._wasm_stext_page_get_first_block(this.pointer)
1500 while (block) {
1501 let block_type = libmupdf._wasm_stext_block_get_type(block)
1502 let block_bbox = fromRect(libmupdf._wasm_stext_block_get_bbox(block))
1503
1504 if (block_type === 0) {
1505 if (walker.beginTextBlock)
1506 walker.beginTextBlock(block_bbox)
1507
1508 let line = libmupdf._wasm_stext_block_get_first_line(block)
1509 while (line) {
1510 let line_bbox = fromRect(libmupdf._wasm_stext_line_get_bbox(line))
1511 let line_wmode = libmupdf._wasm_stext_line_get_wmode(line)
1512 let line_dir = fromPoint(libmupdf._wasm_stext_line_get_dir(line))
1513
1514 if (walker.beginLine)
1515 walker.beginLine(line_bbox, line_wmode, line_dir)
1516
1517 if (walker.onChar) {
1518 let ch = libmupdf._wasm_stext_line_get_first_char(line)
1519 while (ch) {
1520 let ch_rune = String.fromCharCode(libmupdf._wasm_stext_char_get_c(ch))
1521 let ch_origin = fromPoint(libmupdf._wasm_stext_char_get_origin(ch))
1522 let ch_font = new Font(libmupdf._wasm_stext_char_get_font(ch))
1523 let ch_size = libmupdf._wasm_stext_char_get_size(ch)
1524 let ch_quad = fromQuad(libmupdf._wasm_stext_char_get_quad(ch))
1525 let ch_color = colorFromNumber(libmupdf._wasm_stext_char_get_argb(ch))
1526
1527 walker.onChar(ch_rune, ch_origin, ch_font, ch_size, ch_quad, ch_color)
1528
1529 ch = libmupdf._wasm_stext_char_get_next(ch)
1530 }
1531 }
1532
1533 if (walker.endLine)
1534 walker.endLine()
1535
1536 line = libmupdf._wasm_stext_line_get_next(line)
1537 }
1538
1539 if (walker.endTextBlock)
1540 walker.endTextBlock()
1541 } else if (block_type === 1) {
1542 /* image */
1543 if (walker.onImageBlock) {
1544 let matrix = fromMatrix(libmupdf._wasm_stext_block_get_transform(block))
1545 let image = new Image(libmupdf._wasm_stext_block_get_image(block))
1546 walker.onImageBlock(block_bbox, matrix, image)
1547 }
1548 } else if (block_type === 2) {
1549 /* struct */
1550 } else if (block_type === 3) {
1551 /* vector */
1552 if (walker.onVector) {
1553 let v_flags_word = libmupdf._wasm_stext_block_get_v_flags(block)
1554 let v_flags = {
1555 isStroked: !!(v_flags_word & 1),
1556 isRectangle: !!(v_flags_word & 2),
1557 }
1558 let v_color = colorFromNumber(libmupdf._wasm_stext_block_get_v_argb(block))
1559 walker.onVector(block_bbox, v_flags, v_color)
1560 }
1561 } else if (block_type === 4) {
1562 /* grid */
1563 }
1564
1565 block = libmupdf._wasm_stext_block_get_next(block)
1566 }
1567 }
1568
1569 asJSON(scale = 1) {
1570 return fromStringFree(libmupdf._wasm_print_stext_page_as_json(this.pointer, scale))
1571 }
1572
1573 asHTML(id: number) {
1574 return fromStringFree(libmupdf._wasm_print_stext_page_as_html(this.pointer, id))
1575 }
1576
1577 asText() {
1578 return fromStringFree(libmupdf._wasm_print_stext_page_as_text(this.pointer))
1579 }
1580
1581 snap(p: Point, q: Point, mode: SelectMode): Quad {
1582 let mm = ENUM<SelectMode>(mode, StructuredText.SELECT_MODE)
1583 return fromQuad(libmupdf._wasm_snap_selection(this.pointer, POINT(p), POINT2(q), mm))
1584 }
1585
1586 copy(p: Point, q: Point): string {
1587 return fromStringFree(libmupdf._wasm_copy_selection(this.pointer, POINT(p), POINT2(q)))
1588 }
1589
1590 highlight(p: Point, q: Point, max_hits = 100): Quad[] {
1591 let hits = 0 as Pointer<"fz_quad">
1592 let result: Quad[] = []
1593 try {
1594 hits = Malloc<"fz_quad">(32 * max_hits)
1595 let n = libmupdf._wasm_highlight_selection(this.pointer, POINT(p), POINT2(q), hits, max_hits)
1596 for (let i = 0; i < n; ++i)
1597 result.push(fromQuad(hits + i * 32 as Pointer<"fz_quad">))
1598 } finally {
1599 Free(hits)
1600 }
1601 return result
1602 }
1603
1604 search(needle: string, max_hits = 500) {
1605 return runSearch(libmupdf._wasm_search_stext_page, this.pointer, needle, max_hits)
1606 }
1607 }
1608
1609 export type BlendMode =
1610 "Normal" |
1611 "Multiply" |
1612 "Screen" |
1613 "Overlay" |
1614 "Darken" |
1615 "Lighten" |
1616 "ColorDodge" |
1617 "ColorBurn" |
1618 "HardLight" |
1619 "SoftLight" |
1620 "Difference" |
1621 "Exclusion" |
1622 "Hue" |
1623 "Saturation" |
1624 "Color" |
1625 "Luminosity"
1626
1627 export class Device extends Userdata<"fz_device"> {
1628 static override readonly _drop = libmupdf._wasm_drop_device
1629
1630 static readonly BLEND_MODES: BlendMode[] = [
1631 "Normal",
1632 "Multiply",
1633 "Screen",
1634 "Overlay",
1635 "Darken",
1636 "Lighten",
1637 "ColorDodge",
1638 "ColorBurn",
1639 "HardLight",
1640 "SoftLight",
1641 "Difference",
1642 "Exclusion",
1643 "Hue",
1644 "Saturation",
1645 "Color",
1646 "Luminosity",
1647 ]
1648
1649 static readonly BLEND_NORMAL = "Normal"
1650 static readonly BLEND_MULTIPLY = "Multiply"
1651 static readonly BLEND_SCREEN = "Screen"
1652 static readonly BLEND_OVERLAY = "Overlay"
1653 static readonly BLEND_DARKEN = "Darken"
1654 static readonly BLEND_LIGHTEN = "Lighten"
1655 static readonly BLEND_COLOR_DODGE = "ColorDodge"
1656 static readonly BLEND_COLOR_BURN = "ColorBurn"
1657 static readonly BLEND_HARD_LIGHT = "HardLight"
1658 static readonly BLEND_SOFT_LIGHT = "SoftLight"
1659 static readonly BLEND_DIFFERENCE = "Difference"
1660 static readonly BLEND_EXCLUSION = "Exclusion"
1661 static readonly BLEND_HUE = "Hue"
1662 static readonly BLEND_SATURATION = "Saturation"
1663 static readonly BLEND_COLOR = "Color"
1664 static readonly BLEND_LUMINOSITY = "Luminosity"
1665
1666 constructor(callbacks: DeviceFunctions)
1667
1668 // PRIVATE
1669 constructor(pointer: Pointer<"fz_device">)
1670
1671 constructor(pointer_or_callbacks: Pointer<"fz_device"> | DeviceFunctions) {
1672 if (typeof pointer_or_callbacks === "number")
1673 super(pointer_or_callbacks)
1674 else {
1675 let id = $libmupdf_device_id++
1676 $libmupdf_device_table.set(id, pointer_or_callbacks)
1677 super(libmupdf._wasm_new_js_device(id))
1678 }
1679 }
1680
1681 fillPath(path: Path, evenOdd: boolean, ctm: Matrix, colorspace: ColorSpace, color: Color, alpha: number) {
1682 checkType(path, Path)
1683 checkMatrix(ctm)
1684 checkType(colorspace, ColorSpace)
1685 checkColor(color)
1686 libmupdf._wasm_fill_path(this.pointer, path.pointer, evenOdd, MATRIX(ctm), colorspace.pointer, COLOR(color), alpha)
1687 }
1688
1689 strokePath(path: Path, stroke: StrokeState, ctm: Matrix, colorspace: ColorSpace, color: Color, alpha: number) {
1690 checkType(path, Path)
1691 checkType(stroke, StrokeState)
1692 checkMatrix(ctm)
1693 checkType(colorspace, ColorSpace)
1694 checkColor(color)
1695 libmupdf._wasm_stroke_path(
1696 this.pointer,
1697 path.pointer,
1698 stroke.pointer,
1699 MATRIX(ctm),
1700 colorspace.pointer,
1701 COLOR(color),
1702 alpha
1703 )
1704 }
1705
1706 clipPath(path: Path, evenOdd: boolean, ctm: Matrix) {
1707 checkType(path, Path)
1708 checkMatrix(ctm)
1709 libmupdf._wasm_clip_path(this.pointer, path.pointer, evenOdd, MATRIX(ctm))
1710 }
1711
1712 clipStrokePath(path: Path, stroke: StrokeState, ctm: Matrix) {
1713 checkType(path, Path)
1714 checkType(stroke, StrokeState)
1715 checkMatrix(ctm)
1716 libmupdf._wasm_clip_stroke_path(this.pointer, path.pointer, stroke.pointer, MATRIX(ctm))
1717 }
1718
1719 fillText(text: Text, ctm: Matrix, colorspace: ColorSpace, color: Color, alpha: number) {
1720 checkType(text, Text)
1721 checkMatrix(ctm)
1722 checkType(colorspace, ColorSpace)
1723 checkColor(color)
1724 libmupdf._wasm_fill_text(this.pointer, text.pointer, MATRIX(ctm), colorspace.pointer, COLOR(color), alpha)
1725 }
1726
1727 strokeText(text: Text, stroke: StrokeState, ctm: Matrix, colorspace: ColorSpace, color: Color, alpha: number) {
1728 checkType(text, Text)
1729 checkType(stroke, StrokeState)
1730 checkMatrix(ctm)
1731 checkType(colorspace, ColorSpace)
1732 checkColor(color)
1733 libmupdf._wasm_stroke_text(
1734 this.pointer,
1735 text.pointer,
1736 stroke.pointer,
1737 MATRIX(ctm),
1738 colorspace.pointer,
1739 COLOR(color),
1740 alpha
1741 )
1742 }
1743
1744 clipText(text: Text, ctm: Matrix) {
1745 checkType(text, Text)
1746 checkMatrix(ctm)
1747 libmupdf._wasm_clip_text(this.pointer, text.pointer, MATRIX(ctm))
1748 }
1749
1750 clipStrokeText(text: Text, stroke: StrokeState, ctm: Matrix) {
1751 checkType(text, Text)
1752 checkType(stroke, StrokeState)
1753 checkMatrix(ctm)
1754 libmupdf._wasm_clip_stroke_text(this.pointer, text.pointer, stroke.pointer, MATRIX(ctm))
1755 }
1756
1757 ignoreText(text: Text, ctm: Matrix) {
1758 checkType(text, Text)
1759 checkMatrix(ctm)
1760 libmupdf._wasm_ignore_text(this.pointer, text.pointer, MATRIX(ctm))
1761 }
1762
1763 fillShade(shade: Shade, ctm: Matrix, alpha: number) {
1764 checkType(shade, Shade)
1765 checkMatrix(ctm)
1766 libmupdf._wasm_fill_shade(this.pointer, shade.pointer, MATRIX(ctm), alpha)
1767 }
1768
1769 fillImage(image: Image, ctm: Matrix, alpha: number) {
1770 checkType(image, Image)
1771 checkMatrix(ctm)
1772 libmupdf._wasm_fill_image(this.pointer, image.pointer, MATRIX(ctm), alpha)
1773 }
1774
1775 fillImageMask(image: Image, ctm: Matrix, colorspace: ColorSpace, color: Color, alpha: number) {
1776 checkType(image, Image)
1777 checkMatrix(ctm)
1778 checkType(colorspace, ColorSpace)
1779 checkColor(color)
1780 libmupdf._wasm_fill_image_mask(this.pointer, image.pointer, MATRIX(ctm), colorspace.pointer, COLOR(color), alpha)
1781 }
1782
1783 clipImageMask(image: Image, ctm: Matrix) {
1784 checkType(image, Image)
1785 checkMatrix(ctm)
1786 libmupdf._wasm_clip_image_mask(this.pointer, image.pointer, MATRIX(ctm))
1787 }
1788
1789 popClip() {
1790 libmupdf._wasm_pop_clip(this.pointer)
1791 }
1792
1793 beginMask(area: Rect, luminosity: boolean, colorspace: ColorSpace, color: Color) {
1794 checkRect(area)
1795 checkType(colorspace, ColorSpace)
1796 checkColor(color)
1797 libmupdf._wasm_begin_mask(this.pointer, RECT(area), luminosity, colorspace.pointer, COLOR(color))
1798 }
1799
1800 endMask() {
1801 libmupdf._wasm_end_mask(this.pointer)
1802 }
1803
1804 beginGroup(area: Rect, colorspace: ColorSpace, isolated: boolean, knockout: boolean, blendmode: BlendMode, alpha: number) {
1805 checkRect(area)
1806 checkType(colorspace, ColorSpace)
1807 let blendmode_ix = ENUM<BlendMode>(blendmode, Device.BLEND_MODES)
1808 libmupdf._wasm_begin_group(this.pointer, RECT(area), colorspace.pointer, isolated, knockout, blendmode_ix, alpha)
1809 }
1810
1811 endGroup() {
1812 libmupdf._wasm_end_group(this.pointer)
1813 }
1814
1815 beginTile(area: Rect, view: Rect, xstep: number, ystep: number, ctm: Matrix, id: number, doc_id: number) {
1816 checkRect(area)
1817 checkRect(view)
1818 checkMatrix(ctm)
1819 return libmupdf._wasm_begin_tile(this.pointer, RECT(area), RECT2(view), xstep, ystep, MATRIX(ctm), id, doc_id)
1820 }
1821
1822 endTile() {
1823 libmupdf._wasm_end_tile(this.pointer)
1824 }
1825
1826 beginLayer(name: string) {
1827 libmupdf._wasm_begin_layer(this.pointer, STRING(name))
1828 }
1829
1830 endLayer() {
1831 libmupdf._wasm_end_layer(this.pointer)
1832 }
1833
1834 close() {
1835 libmupdf._wasm_close_device(this.pointer)
1836 }
1837 }
1838
1839 export class DrawDevice extends Device {
1840 constructor(matrix: Matrix, pixmap: Pixmap) {
1841 checkMatrix(matrix)
1842 checkType(pixmap, Pixmap)
1843 super(libmupdf._wasm_new_draw_device(MATRIX(matrix), pixmap.pointer))
1844 }
1845 }
1846
1847 export class DisplayListDevice extends Device {
1848 constructor(displayList: DisplayList) {
1849 checkType(displayList, DisplayList)
1850 super(libmupdf._wasm_new_display_list_device(displayList.pointer))
1851 }
1852 }
1853
1854 export class DocumentWriter extends Userdata<"fz_document_writer"> {
1855 static override readonly _drop = libmupdf._wasm_drop_document_writer
1856
1857 constructor(buffer: Buffer, format: string, options: string) {
1858 super(
1859 libmupdf._wasm_new_document_writer_with_buffer(
1860 BUFFER(buffer),
1861 STRING(format),
1862 STRING2(options)
1863 )
1864 )
1865 }
1866
1867 beginPage(mediabox: Rect) {
1868 checkRect(mediabox)
1869 return new Device(
1870 libmupdf._wasm_keep_device(
1871 libmupdf._wasm_begin_page(this.pointer, RECT(mediabox))
1872 )
1873 )
1874 }
1875
1876 endPage() {
1877 libmupdf._wasm_end_page(this.pointer)
1878 }
1879
1880 close() {
1881 libmupdf._wasm_close_document_writer(this.pointer)
1882 }
1883 }
1884
1885 export type DocumentPermission =
1886 "print" |
1887 "copy" |
1888 "edit" |
1889 "annotate" |
1890 "form" |
1891 "accessibility" |
1892 "assemble" |
1893 "print-hq"
1894
1895 export class LinkDestination {
1896 static readonly LINK_DEST: LinkDestType[] = [
1897 "Fit",
1898 "FitB",
1899 "FitH",
1900 "FitBH",
1901 "FitV",
1902 "FitBV",
1903 "FitR",
1904 "XYZ",
1905 ]
1906
1907 static readonly FIT = "Fit"
1908 static readonly FIT_B = "FitB"
1909 static readonly FIT_H = "FitH"
1910 static readonly FIT_BH = "FitBH"
1911 static readonly FIT_V = "FitV"
1912 static readonly FIT_BV = "FitBV"
1913 static readonly FIT_R = "FitR"
1914 static readonly XYZ = "XYZ"
1915
1916 type: LinkDestType
1917 chapter: number
1918 page: number
1919 x: number
1920 y: number
1921 width: number
1922 height: number
1923 zoom: number
1924
1925 constructor(chapter=0, page=0, type:LinkDestType="Fit", x=NaN, y=NaN, width=NaN, height=NaN, zoom=NaN) {
1926 this.chapter = chapter
1927 this.page = page
1928 this.type = type
1929 this.x = x
1930 this.y = y
1931 this.width = width
1932 this.height = height
1933 this.zoom = zoom
1934 }
1935 }
1936
1937 export class Document extends Userdata<"any_document"> {
1938 static override readonly _drop = libmupdf._wasm_drop_document
1939
1940 static readonly META_FORMAT = "format"
1941 static readonly META_ENCRYPTION = "encryption"
1942 static readonly META_INFO_AUTHOR = "info:Author"
1943 static readonly META_INFO_TITLE = "info:Title"
1944 static readonly META_INFO_SUBJECT = "info:Subject"
1945 static readonly META_INFO_KEYWORDS = "info:Keywords"
1946 static readonly META_INFO_CREATOR = "info:Creator"
1947 static readonly META_INFO_PRODUCER = "info:Producer"
1948 static readonly META_INFO_CREATIONDATE = "info:CreationDate"
1949 static readonly META_INFO_MODIFICATIONDATE = "info:ModDate"
1950
1951 static readonly PERMISSION_PRINT = "print"
1952 static readonly PERMISSION_COPY = "copy"
1953 static readonly PERMISSION_EDIT = "eedit"
1954 static readonly PERMISSION_ANNOTATE = "annotate"
1955 static readonly PERMISSION_FORM = "form"
1956 static readonly PERMISSION_ACCESSIBILITY = "accessibility"
1957 static readonly PERMISSION_ASSEMBLE = "assemble"
1958 static readonly PERMISSION_PRINT_HQ = "print-hq"
1959
1960 static readonly PERMISSION: Record<DocumentPermission,number> = {
1961 "print": "p".charCodeAt(0),
1962 "copy": "c".charCodeAt(0),
1963 "edit": "e".charCodeAt(0),
1964 "annotate": "n".charCodeAt(0),
1965 "form": "f".charCodeAt(0),
1966 "accessibility": "y".charCodeAt(0),
1967 "assemble": "a".charCodeAt(0),
1968 "print-hq": "h".charCodeAt(0),
1969 }
1970
1971 static openDocument(from: Buffer | ArrayBuffer | Uint8Array | Stream | string, magic?: string): Document {
1972 let pointer = 0 as Pointer<"any_document">
1973 let free_from = false
1974
1975 if (typeof from === "string") {
1976 magic = from
1977 if (node_fs)
1978 from = node_fs.readFileSync(from)
1979 else
1980 throw new Error("missing 'fs' module")
1981 } else {
1982 if (typeof magic === "undefined")
1983 magic = "application/pdf"
1984 }
1985
1986 checkType(magic, "string")
1987
1988 if (from instanceof ArrayBuffer || from instanceof Uint8Array) {
1989 from = new Buffer(from)
1990 free_from = true
1991 }
1992 if (from instanceof Buffer)
1993 pointer = libmupdf._wasm_open_document_with_buffer(STRING(magic), from.pointer)
1994 else if (from instanceof Stream)
1995 pointer = libmupdf._wasm_open_document_with_stream(STRING(magic), from.pointer)
1996 else
1997 throw new Error("not a Buffer or Stream")
1998
1999 if (free_from) {
2000 // Destroy any implicit Buffer instances immediately!
2001 // This may help the GC and FinalizationRegistry out when
2002 // processing many documents without a pause.
2003 from.destroy()
2004 }
2005
2006 let pdf = libmupdf._wasm_pdf_document_from_fz_document(pointer)
2007 if (pdf)
2008 return new PDFDocument(pdf)
2009
2010 return new Document(pointer)
2011 }
2012
2013 formatLinkURI(dest: LinkDest) {
2014 return fromStringFree(
2015 libmupdf._wasm_format_link_uri(this.pointer,
2016 dest.chapter | 0,
2017 dest.page | 0,
2018 ENUM<LinkDestType>(dest.type, LinkDestination.LINK_DEST),
2019 +dest.x,
2020 +dest.y,
2021 +dest.width,
2022 +dest.height,
2023 +dest.zoom
2024 )
2025 )
2026 }
2027
2028 asPDF() {
2029 if (this instanceof PDFDocument)
2030 return this
2031 return null
2032 }
2033
2034 isPDF() {
2035 return this instanceof PDFDocument
2036 }
2037
2038 needsPassword() {
2039 return !!libmupdf._wasm_needs_password(this.pointer)
2040 }
2041
2042 authenticatePassword(password: string) {
2043 return libmupdf._wasm_authenticate_password(this.pointer, STRING(password))
2044 }
2045
2046 hasPermission(perm: DocumentPermission) {
2047 let perm_ix = (typeof perm === "number") ? perm : Document.PERMISSION[perm]
2048 return !!libmupdf._wasm_has_permission(this.pointer, perm_ix)
2049 }
2050
2051 getMetaData(key: string) {
2052 let value = libmupdf._wasm_lookup_metadata(this.pointer, STRING(key))
2053 if (value)
2054 return fromString(value)
2055 return undefined
2056 }
2057
2058 setMetaData(key: string, value: string) {
2059 libmupdf._wasm_set_metadata(this.pointer, STRING(key), STRING2(value))
2060 }
2061
2062 countPages() {
2063 return libmupdf._wasm_count_pages(this.pointer)
2064 }
2065
2066 isReflowable() {
2067 libmupdf._wasm_is_document_reflowable(this.pointer)
2068 }
2069
2070 layout(w: number, h: number, em: number) {
2071 libmupdf._wasm_layout_document(this.pointer, w, h, em)
2072 }
2073
2074 loadPage(index: number) {
2075 let fz_ptr = libmupdf._wasm_load_page(this.pointer, index)
2076 if (this instanceof PDFDocument) {
2077 let pdf_ptr = libmupdf._wasm_pdf_page_from_fz_page(fz_ptr)
2078 if (pdf_ptr)
2079 return new PDFPage(this, pdf_ptr)
2080 }
2081 return new Page(fz_ptr)
2082 }
2083
2084 loadOutline() {
2085 let doc = this.pointer
2086 function to_outline(outline: Pointer<"fz_outline">) {
2087 let result: OutlineItem[] = []
2088 while (outline) {
2089 let title = libmupdf._wasm_outline_get_title(outline)
2090 let uri = libmupdf._wasm_outline_get_uri(outline)
2091 let open = libmupdf._wasm_outline_get_is_open(outline)
2092
2093 let item: OutlineItem = {
2094 title: title ? fromString(title) : undefined,
2095 uri: uri ? fromString(uri) : undefined,
2096 open: !!open,
2097 }
2098
2099 let page = libmupdf._wasm_outline_get_page(doc, outline)
2100 if (page >= 0)
2101 item.page = page
2102
2103 let down = libmupdf._wasm_outline_get_down(outline)
2104 if (down)
2105 item.down = to_outline(down)
2106
2107 result.push(item)
2108
2109 outline = libmupdf._wasm_outline_get_next(outline)
2110 }
2111 return result
2112 }
2113 let root = libmupdf._wasm_load_outline(doc)
2114 if (root)
2115 return to_outline(root)
2116 return null
2117 }
2118
2119 resolveLink(link: string | Link) {
2120 if (link instanceof Link)
2121 return libmupdf._wasm_resolve_link(this.pointer, libmupdf._wasm_link_get_uri(link.pointer))
2122 return libmupdf._wasm_resolve_link(this.pointer, STRING(link))
2123 }
2124
2125 resolveLinkDestination(link: string | Link): LinkDest {
2126 let dest: Pointer<"fz_link_dest">
2127 if (link instanceof Link)
2128 dest = libmupdf._wasm_resolve_link_dest(this.pointer, libmupdf._wasm_link_get_uri(link.pointer))
2129 else
2130 dest = libmupdf._wasm_resolve_link_dest(this.pointer, STRING(link))
2131 return {
2132 type: LinkDestination.LINK_DEST[libmupdf._wasm_link_dest_get_type(dest)] as LinkDestType,
2133 chapter: libmupdf._wasm_link_dest_get_chapter(dest),
2134 page: libmupdf._wasm_link_dest_get_page(dest),
2135 x: libmupdf._wasm_link_dest_get_x(dest),
2136 y: libmupdf._wasm_link_dest_get_y(dest),
2137 width: libmupdf._wasm_link_dest_get_w(dest),
2138 height: libmupdf._wasm_link_dest_get_h(dest),
2139 zoom: libmupdf._wasm_link_dest_get_zoom(dest),
2140 }
2141 }
2142
2143 outlineIterator() {
2144 return new OutlineIterator(libmupdf._wasm_new_outline_iterator(this.pointer))
2145 }
2146 }
2147
2148 interface OutlineItem {
2149 title: string | undefined,
2150 uri: string | undefined,
2151 open: boolean,
2152 down?: OutlineItem[],
2153 page?: number,
2154 }
2155
2156 export class OutlineIterator extends Userdata<"fz_outline_iterator"> {
2157 static override readonly _drop = libmupdf._wasm_drop_outline_iterator
2158
2159 static readonly ITERATOR_DID_NOT_MOVE = -1
2160 static readonly ITERATOR_AT_ITEM = 0
2161 static readonly ITERATOR_AT_EMPTY = 1
2162
2163 static readonly FLAG_BOLD = 1
2164 static readonly FLAG_ITALIC = 2
2165
2166 item() {
2167 let item = libmupdf._wasm_outline_iterator_item(this.pointer)
2168 if (item) {
2169 let title_ptr = libmupdf._wasm_outline_item_get_title(item)
2170 let uri_ptr = libmupdf._wasm_outline_item_get_uri(item)
2171 let is_open = libmupdf._wasm_outline_item_get_is_open(item)
2172 return {
2173 title: title_ptr ? fromString(title_ptr) : undefined,
2174 uri: uri_ptr ? fromString(uri_ptr) : undefined,
2175 open: !!is_open,
2176 } as OutlineItem
2177 }
2178 return null
2179 }
2180
2181 next() {
2182 return libmupdf._wasm_outline_iterator_next(this.pointer)
2183 }
2184
2185 prev() {
2186 return libmupdf._wasm_outline_iterator_prev(this.pointer)
2187 }
2188
2189 up() {
2190 return libmupdf._wasm_outline_iterator_up(this.pointer)
2191 }
2192
2193 down() {
2194 return libmupdf._wasm_outline_iterator_down(this.pointer)
2195 }
2196
2197 delete() {
2198 return libmupdf._wasm_outline_iterator_delete(this.pointer)
2199 }
2200
2201 insert(item: OutlineItem) {
2202 return libmupdf._wasm_outline_iterator_insert(this.pointer, STRING_OPT(item.title), STRING2_OPT(item.uri), item.open)
2203 }
2204
2205 update(item: OutlineItem) {
2206 libmupdf._wasm_outline_iterator_update(this.pointer, STRING_OPT(item.title), STRING2_OPT(item.uri), item.open)
2207 }
2208 }
2209
2210 export type LinkDestType =
2211 "Fit" |
2212 "FitB" |
2213 "FitH" |
2214 "FitBH" |
2215 "FitV" |
2216 "FitBV" |
2217 "FitR" |
2218 "XYZ"
2219
2220 interface LinkDest {
2221 type: LinkDestType,
2222 chapter: number,
2223 page: number,
2224 x: number,
2225 y: number,
2226 width: number,
2227 height: number,
2228 zoom: number,
2229 }
2230
2231 export class Link extends Userdata<"fz_link"> {
2232 static override readonly _drop = libmupdf._wasm_drop_link
2233
2234 getBounds() {
2235 return fromRect(libmupdf._wasm_link_get_rect(this.pointer))
2236 }
2237
2238 setBounds(rect: Rect) {
2239 checkRect(rect)
2240 libmupdf._wasm_link_set_rect(this.pointer, RECT(rect))
2241 }
2242
2243 getURI() {
2244 return fromString(libmupdf._wasm_link_get_uri(this.pointer))
2245 }
2246
2247 setURI(uri: string) {
2248 checkType(uri, "string")
2249 libmupdf._wasm_link_set_uri(this.pointer, STRING(uri))
2250 }
2251
2252 isExternal() {
2253 return /^\w[\w+-.]*:/.test(this.getURI())
2254 }
2255 }
2256
2257 export type PageBox = "MediaBox" | "CropBox" | "BleedBox" | "TrimBox" | "ArtBox"
2258
2259 export class Page extends Userdata<"any_page"> {
2260 static override readonly _drop = libmupdf._wasm_drop_page
2261
2262 static readonly BOXES: PageBox[] = [
2263 "MediaBox",
2264 "CropBox",
2265 "BleedBox",
2266 "TrimBox",
2267 "ArtBox"
2268 ]
2269
2270 static readonly MEDIA_BOX = "MediaBox"
2271 static readonly CROP_BOX = "CropBox"
2272 static readonly BLEED_BOX = "BleedBox"
2273 static readonly TRIM_BOX = "TrimBox"
2274 static readonly ART_BOX = "ArtBox"
2275
2276 isPDF() {
2277 return this instanceof PDFPage
2278 }
2279
2280 getBounds(box: PageBox = "CropBox") {
2281 let box_ix = ENUM<PageBox>(box, Page.BOXES)
2282 return fromRect(libmupdf._wasm_bound_page(this.pointer, box_ix))
2283 }
2284
2285 getLabel() {
2286 return fromString(libmupdf._wasm_page_label(this.pointer))
2287 }
2288
2289 run(device: Device, matrix: Matrix) {
2290 checkType(device, Device)
2291 checkMatrix(matrix)
2292 libmupdf._wasm_run_page(this.pointer, device.pointer, MATRIX(matrix))
2293 }
2294
2295 runPageContents(device: Device, matrix: Matrix) {
2296 checkType(device, Device)
2297 checkMatrix(matrix)
2298 libmupdf._wasm_run_page_contents(this.pointer, device.pointer, MATRIX(matrix))
2299 }
2300
2301 runPageAnnots(device: Device, matrix: Matrix) {
2302 checkType(device, Device)
2303 checkMatrix(matrix)
2304 libmupdf._wasm_run_page_annots(this.pointer, device.pointer, MATRIX(matrix))
2305 }
2306
2307 runPageWidgets(device: Device, matrix: Matrix) {
2308 checkType(device, Device)
2309 checkMatrix(matrix)
2310 libmupdf._wasm_run_page_widgets(this.pointer, device.pointer, MATRIX(matrix))
2311 }
2312
2313 toPixmap(matrix: Matrix, colorspace: ColorSpace, alpha = false, showExtras = true) {
2314 checkType(colorspace, ColorSpace)
2315 checkMatrix(matrix)
2316 let result
2317 if (showExtras)
2318 result = libmupdf._wasm_new_pixmap_from_page(this.pointer,
2319 MATRIX(matrix),
2320 colorspace.pointer,
2321 alpha)
2322 else
2323 result = libmupdf._wasm_new_pixmap_from_page_contents(this.pointer,
2324 MATRIX(matrix),
2325 colorspace.pointer,
2326 alpha)
2327 return new Pixmap(result)
2328 }
2329
2330 toDisplayList(showExtras = true) {
2331 let result
2332 if (showExtras)
2333 result = libmupdf._wasm_new_display_list_from_page(this.pointer)
2334 else
2335 result = libmupdf._wasm_new_display_list_from_page_contents(this.pointer)
2336 return new DisplayList(result)
2337 }
2338
2339 toStructuredText(options = "") {
2340 checkType(options, "string")
2341 return new StructuredText(libmupdf._wasm_new_stext_page_from_page(this.pointer, STRING(options)))
2342 }
2343
2344 getLinks() {
2345 let links: Link[] = []
2346 let link = libmupdf._wasm_load_links(this.pointer)
2347 while (link) {
2348 links.push(new Link(libmupdf._wasm_keep_link(link)))
2349 link = libmupdf._wasm_link_get_next(link)
2350 }
2351 return links
2352 }
2353
2354 createLink(bbox: Rect, uri: string) {
2355 checkRect(bbox)
2356 return new Link(libmupdf._wasm_create_link(this.pointer, RECT(bbox), STRING(uri)))
2357 }
2358
2359 deleteLink(link: Link) {
2360 checkType(link, Link)
2361 libmupdf._wasm_delete_link(this.pointer, link.pointer)
2362 }
2363
2364 search(needle: string, max_hits = 500) {
2365 return runSearch(libmupdf._wasm_search_page, this.pointer, needle, max_hits)
2366 }
2367
2368 }
2369
2370 /* -------------------------------------------------------------------------- */
2371
2372 export class PDFDocument extends Document {
2373 // Create a new empty document
2374 constructor()
2375
2376 // Open an existing document
2377 constructor(filename: string)
2378 constructor(data: Buffer | ArrayBuffer | Uint8Array | Stream)
2379
2380 // PRIVATE
2381 constructor(clone: PDFDocument)
2382 constructor(pointer: Pointer<"any_document">)
2383
2384 constructor(arg1?: Pointer<"any_document"> | Buffer | ArrayBuffer | Uint8Array | Stream | PDFDocument | string) {
2385 if (typeof arg1 === "undefined")
2386 super(libmupdf._wasm_pdf_create_document())
2387 else if (typeof arg1 === "number")
2388 super(arg1)
2389 else if (arg1 instanceof PDFDocument) {
2390 super(arg1.pointer)
2391 libmupdf._wasm_keep_document(this.pointer)
2392 } else {
2393 let doc = Document.openDocument(arg1, "application/pdf")
2394 if (doc instanceof PDFDocument)
2395 return doc
2396 throw new Error("not a PDF document")
2397 }
2398 }
2399
2400 override loadPage(index: number) {
2401 return super.loadPage(index) as PDFPage
2402 }
2403
2404 // PDFObject instances are always bound to a document, so the WASM/JS value interface lives here.
2405
2406 // Wrap a pdf_obj in a Userdata object. The pointer must be newly created or we already own it.
2407 _fromPDFObjectNew(ptr: Pointer<"pdf_obj">) {
2408 if (ptr === 0)
2409 return PDFObject.Null
2410 return new PDFObject(this, ptr)
2411 }
2412
2413 // Wrap a pdf_obj in a Userdata object. The pointer must be a borrowed pointer, so we have to take ownership.
2414 _fromPDFObjectKeep(ptr: Pointer<"pdf_obj">) {
2415 if (ptr === 0)
2416 return PDFObject.Null
2417 return new PDFObject(this, libmupdf._wasm_pdf_keep_obj(ptr))
2418 }
2419
2420 _toPDFObject(obj: any) {
2421 if (obj instanceof PDFObject)
2422 return obj
2423 if (obj === null || obj === undefined)
2424 return this.newNull()
2425 if (typeof obj === "string") {
2426 // if a JS string is surrounded by parens, convert it to a PDF string
2427 if (obj.startsWith("(") && obj.endsWith(")"))
2428 return this.newString(obj.slice(1, -1))
2429 // otherwise treat it as a name
2430 return this.newName(obj)
2431 }
2432 if (typeof obj === "number") {
2433 if (obj === (obj | 0))
2434 return this.newInteger(obj)
2435 return this.newReal(obj)
2436 }
2437 if (typeof obj === "boolean")
2438 return this.newBoolean(obj)
2439 if (obj instanceof Array) {
2440 let result = this.newArray()
2441 for (let item of obj)
2442 result.push(item)
2443 return result
2444 }
2445 if (obj instanceof Object) {
2446 let result = this.newDictionary()
2447 for (let key in obj)
2448 result.put(key, obj[key])
2449 return result
2450 }
2451 throw new TypeError("cannot convert value to PDFObject")
2452 }
2453
2454 _PDFOBJ(obj: any) {
2455 // Note: We have to create a PDFObject instance for garbage collection.
2456 return this._toPDFObject(obj).pointer
2457 }
2458
2459 getVersion() {
2460 return libmupdf._wasm_pdf_version(this.pointer)
2461 }
2462
2463 getLanguage() {
2464 return fromStringOrNull(libmupdf._wasm_pdf_document_language(this.pointer))
2465 }
2466
2467 setLanguage(lang: string) {
2468 libmupdf._wasm_pdf_set_document_language(this.pointer, STRING(lang))
2469 }
2470
2471 countObjects() {
2472 return libmupdf._wasm_pdf_xref_len(this.pointer)
2473 }
2474
2475 getTrailer() {
2476 return new PDFObject(this, libmupdf._wasm_pdf_trailer(this.pointer))
2477 }
2478
2479 createObject() {
2480 let num = libmupdf._wasm_pdf_create_object(this.pointer)
2481 return this._fromPDFObjectNew(libmupdf._wasm_pdf_new_indirect(this.pointer, num))
2482 }
2483
2484 newNull() { return PDFObject.Null }
2485 newBoolean(v: boolean) { return this._fromPDFObjectNew(libmupdf._wasm_pdf_new_bool(v)) }
2486 newInteger(v: number) { return this._fromPDFObjectNew(libmupdf._wasm_pdf_new_int(v)) }
2487 newReal(v: number) { return this._fromPDFObjectNew(libmupdf._wasm_pdf_new_real(v)) }
2488 newName(v: string) { return this._fromPDFObjectNew(libmupdf._wasm_pdf_new_name(STRING(v))) }
2489 newString(v: string) { return this._fromPDFObjectNew(libmupdf._wasm_pdf_new_text_string(STRING(v))) }
2490
2491 newByteString(v: Uint8Array | number[]) {
2492 if (v instanceof Array)
2493 v = Uint8Array.from(v)
2494 checkType(v, Uint8Array)
2495 let len = v.byteLength
2496 let ptr = Malloc<"char">(len)
2497 libmupdf.HEAPU8.set(v, ptr)
2498 try {
2499 return this._fromPDFObjectNew(libmupdf._wasm_pdf_new_string(ptr, len))
2500 } finally {
2501 Free(ptr)
2502 }
2503 }
2504
2505 newIndirect(v: number) { return this._fromPDFObjectNew(libmupdf._wasm_pdf_new_indirect(this.pointer, v)) }
2506 newArray() { return this._fromPDFObjectNew(libmupdf._wasm_pdf_new_array(this.pointer)) }
2507 newDictionary() { return this._fromPDFObjectNew(libmupdf._wasm_pdf_new_dict(this.pointer)) }
2508
2509 deleteObject(num: number | PDFObject) {
2510 if (num instanceof PDFObject)
2511 num = num.asIndirect()
2512 else
2513 checkType(num, "number")
2514 libmupdf._wasm_pdf_delete_object(this.pointer, num)
2515 }
2516
2517 addObject(obj: any) {
2518 return this._fromPDFObjectNew(libmupdf._wasm_pdf_add_object(this.pointer, this._PDFOBJ(obj)))
2519 }
2520
2521 addStream(buf: AnyBuffer, obj: any) {
2522 return this._fromPDFObjectNew(libmupdf._wasm_pdf_add_stream(this.pointer, BUFFER(buf), this._PDFOBJ(obj), 0))
2523 }
2524
2525 addRawStream(buf: AnyBuffer, obj: any) {
2526 return this._fromPDFObjectNew(libmupdf._wasm_pdf_add_stream(this.pointer, BUFFER(buf), this._PDFOBJ(obj), 1))
2527 }
2528
2529 newGraftMap() {
2530 return new PDFGraftMap(this, libmupdf._wasm_pdf_new_graft_map(this.pointer))
2531 }
2532
2533 graftObject(obj: PDFObject) {
2534 checkType(obj, PDFObject)
2535 return this._fromPDFObjectNew(libmupdf._wasm_pdf_graft_object(this.pointer, obj.pointer))
2536 }
2537
2538 graftPage(to: number, srcDoc: PDFDocument, srcPage: number) {
2539 checkType(to, "number")
2540 checkType(srcDoc, PDFDocument)
2541 checkType(srcPage, "number")
2542 libmupdf._wasm_pdf_graft_page(this.pointer, to, srcDoc.pointer, srcPage)
2543 }
2544
2545 addSimpleFont(font: Font, encoding: FontSimpleEncoding = "Latin") {
2546 checkType(font, Font)
2547 var encoding_ix = ENUM<FontSimpleEncoding>(encoding, Font.SIMPLE_ENCODING)
2548 return this._fromPDFObjectNew(libmupdf._wasm_pdf_add_simple_font(this.pointer, font.pointer, encoding_ix))
2549 }
2550
2551 addCJKFont(font: Font, lang: FontCJKOrdering | FontCJKLanguage, wmode = 0, serif = true) {
2552 checkType(font, Font)
2553 if (typeof lang === "string")
2554 lang = Font.CJK_ORDERING_BY_LANG[lang]
2555 return this._fromPDFObjectNew(libmupdf._wasm_pdf_add_cjk_font(this.pointer, font.pointer, lang, wmode, serif))
2556 }
2557
2558 addFont(font: Font) {
2559 checkType(font, Font)
2560 return this._fromPDFObjectNew(libmupdf._wasm_pdf_add_cid_font(this.pointer, font.pointer))
2561 }
2562
2563 addImage(image: Image) {
2564 checkType(image, Image)
2565 return this._fromPDFObjectNew(libmupdf._wasm_pdf_add_image(this.pointer, image.pointer))
2566 }
2567
2568 loadImage(ref: PDFObject) {
2569 checkType(ref, PDFObject)
2570 return new Image(libmupdf._wasm_pdf_load_image(this.pointer, ref.pointer))
2571 }
2572
2573 findPage(index: number) {
2574 checkType(index, "number")
2575 return this._fromPDFObjectKeep(libmupdf._wasm_pdf_lookup_page_obj(this.pointer, index))
2576 }
2577
2578 setPageTreeCache(enabled: boolean) {
2579 checkType(enabled, "boolean")
2580 libmupdf._wasm_pdf_set_page_tree_cache(this.pointer, enabled)
2581 }
2582
2583 addPage(mediabox: Rect, rotate: Rotate, resources: any, contents: AnyBuffer) {
2584 checkRect(mediabox)
2585 checkType(rotate, "number")
2586 return this._fromPDFObjectNew(
2587 libmupdf._wasm_pdf_add_page(
2588 this.pointer,
2589 RECT(mediabox),
2590 rotate,
2591 this._PDFOBJ(resources),
2592 BUFFER(contents)
2593 )
2594 )
2595 }
2596
2597 insertPage(at: number, obj: PDFObject) {
2598 checkType(at, "number")
2599 libmupdf._wasm_pdf_insert_page(this.pointer, at, this._PDFOBJ(obj))
2600 }
2601
2602 deletePage(at: number) {
2603 checkType(at, "number")
2604 libmupdf._wasm_pdf_delete_page(this.pointer, at)
2605 }
2606
2607 isEmbeddedFile(ref: PDFObject) {
2608 checkType(ref, PDFObject)
2609 return !!libmupdf._wasm_pdf_is_embedded_file(ref.pointer)
2610 }
2611
2612 addEmbeddedFile(filename: string, mimetype: string, contents: AnyBuffer, created: Date, modified: Date, checksum = false) {
2613 checkType(filename, "string")
2614 checkType(mimetype, "string")
2615 checkType(created, Date)
2616 checkType(modified, Date)
2617 checkType(checksum, "boolean")
2618 return this._fromPDFObjectNew(
2619 libmupdf._wasm_pdf_add_embedded_file(
2620 this.pointer,
2621 STRING(filename),
2622 STRING2(mimetype),
2623 BUFFER(contents),
2624 created.getTime() / 1000 | 0,
2625 modified.getTime() / 1000 | 0,
2626 checksum
2627 )
2628 )
2629 }
2630
2631 getFilespecParams(ref: PDFObject) {
2632 checkType(ref, PDFObject)
2633 let ptr = libmupdf._wasm_pdf_get_filespec_params(ref.pointer)
2634 return {
2635 filename:
2636 fromString(libmupdf._wasm_pdf_filespec_params_get_filename(ptr)),
2637 mimetype:
2638 fromString(libmupdf._wasm_pdf_filespec_params_get_mimetype(ptr)),
2639 size:
2640 libmupdf._wasm_pdf_filespec_params_get_filename(ptr),
2641 creationDate:
2642 new Date(libmupdf._wasm_pdf_filespec_params_get_created(ptr) * 1000),
2643 modificationDate:
2644 new Date(libmupdf._wasm_pdf_filespec_params_get_modified(ptr) * 1000),
2645 }
2646 }
2647
2648 getEmbeddedFileContents(ref: PDFObject) {
2649 checkType(ref, PDFObject)
2650 let contents = libmupdf._wasm_pdf_load_embedded_file_contents(ref.pointer)
2651 if (contents)
2652 return new Buffer(contents)
2653 return null
2654 }
2655
2656 getEmbeddedFiles(): Record<string,PDFObject> {
2657 function _getEmbeddedFilesRec(result: Record<string,PDFObject>, N: PDFObject) {
2658 var i, n
2659 if (N.isDictionary()) {
2660 var NN = N.get("Names")
2661 if (NN)
2662 for (i = 0, n = NN.length; i < n; i += 2)
2663 result[NN.get(i+0).asString()] = NN.get(i+1)
2664 var NK = N.get("Kids")
2665 if (NK)
2666 for (i = 0, n = NK.length; i < n; i += 1)
2667 _getEmbeddedFilesRec(result, NK.get(i))
2668 }
2669 return result
2670 }
2671 return _getEmbeddedFilesRec({}, this.getTrailer().get("Root", "Names", "EmbeddedFiles"))
2672 }
2673
2674 loadNameTree(treeName: string): Record<string,PDFObject> {
2675 function _loadNameTreeRec(dict: Record<string,PDFObject>, node: PDFObject) {
2676 var kids = node.get("Kids")
2677 if (kids && kids.isArray())
2678 for (var i = 0; i < kids.length; i += 1)
2679 _loadNameTreeRec(dict, kids.get(i))
2680 var names = node.get("Names")
2681 if (names && names.isArray())
2682 for (var i = 0; i < names.length; i += 2)
2683 dict[names.get(i).asString()] = names.get(i+1)
2684 }
2685 var node = this.getTrailer().get("Root").get("Names").get(treeName)
2686 var dict = {}
2687 if (node.isDictionary())
2688 _loadNameTreeRec(dict, node)
2689 return dict
2690 }
2691
2692 insertEmbeddedFile(filename: string, filespec: PDFObject) {
2693 var efs = this.getEmbeddedFiles()
2694 efs[filename] = filespec
2695 this._rewriteEmbeddedFiles(efs)
2696 }
2697
2698 deleteEmbeddedFile(filename: string) {
2699 var efs = this.getEmbeddedFiles()
2700 delete efs[filename]
2701 this._rewriteEmbeddedFiles(efs)
2702 }
2703
2704 _rewriteEmbeddedFiles(efs: Record<string,PDFObject>) {
2705 var efs_keys = Object.keys(efs)
2706 efs_keys.sort()
2707 var root = this.getTrailer().get("Root")
2708 var root_names = root.get("Names")
2709 if (!root_names.isDictionary())
2710 root_names = root.put("Names", this.newDictionary())
2711 var root_names_efs = root_names.put("EmbeddedFiles", this.newDictionary())
2712 var root_names_efs_names = root_names_efs.put("Names", this.newArray())
2713 for (var key of efs_keys) {
2714 root_names_efs_names.push(this.newString(key))
2715 root_names_efs_names.push(efs[key])
2716 }
2717 }
2718
2719 saveToBuffer(options: string | Record<string,any> = "") {
2720 var options_string
2721 if (typeof options === "object") {
2722 options_string = Object.entries(options).map(kv => {
2723 var k: string = kv[0]
2724 var v: any = kv[1]
2725 if (v === true)
2726 return k + "=" + "yes"
2727 else if (v === false)
2728 return k + "=" + "no"
2729 else
2730 return k + "=" + String(v).replaceAll(",", ":")
2731 }).join(",")
2732 } else {
2733 options_string = options
2734 }
2735 return new Buffer(libmupdf._wasm_pdf_write_document_buffer(this.pointer, STRING(options_string)))
2736 }
2737
2738 save(filename: string, options: string | Record<string,any> = "") {
2739 if (node_fs)
2740 node_fs.writeFileSync(filename, this.saveToBuffer(options).asUint8Array())
2741 else
2742 throw new Error("missing 'fs' module")
2743 }
2744
2745 static readonly PAGE_LABEL_NONE = "\0"
2746 static readonly PAGE_LABEL_DECIMAL = "D"
2747 static readonly PAGE_LABEL_ROMAN_UC = "R"
2748 static readonly PAGE_LABEL_ROMAN_LC = "r"
2749 static readonly PAGE_LABEL_ALPHA_UC = "A"
2750 static readonly PAGE_LABEL_ALPHA_LC = "a"
2751
2752 setPageLabels(index: number, style = "D", prefix = "", start = 1) {
2753 libmupdf._wasm_pdf_set_page_labels(this.pointer, index, style.charCodeAt(0), STRING(prefix), start)
2754 }
2755
2756 deletePageLabels(index: number) {
2757 libmupdf._wasm_pdf_delete_page_labels(this.pointer, index)
2758 }
2759
2760 wasRepaired() {
2761 return !!libmupdf._wasm_pdf_was_repaired(this.pointer)
2762 }
2763
2764 hasUnsavedChanges() {
2765 return !!libmupdf._wasm_pdf_has_unsaved_changes(this.pointer)
2766 }
2767
2768 countVersions() {
2769 return libmupdf._wasm_pdf_count_versions(this.pointer)
2770 }
2771
2772 countUnsavedVersions() {
2773 return libmupdf._wasm_pdf_count_unsaved_versions(this.pointer)
2774 }
2775
2776 validateChangeHistory() {
2777 return libmupdf._wasm_pdf_validate_change_history(this.pointer)
2778 }
2779
2780 canBeSavedIncrementally() {
2781 return !!libmupdf._wasm_pdf_can_be_saved_incrementally(this.pointer)
2782 }
2783
2784 enableJournal() {
2785 libmupdf._wasm_pdf_enable_journal(this.pointer)
2786 }
2787
2788 getJournal() {
2789 let position = libmupdf._wasm_pdf_undoredo_state_position(this.pointer)
2790 let n = libmupdf._wasm_pdf_undoredo_state_count(this.pointer)
2791 let steps: string[] = []
2792 for (let i = 0; i < n; ++i)
2793 steps.push(
2794 fromString(
2795 libmupdf._wasm_pdf_undoredo_step(this.pointer, i),
2796 )
2797 )
2798 return { position, steps }
2799 }
2800
2801 beginOperation(op: string) {
2802 libmupdf._wasm_pdf_begin_operation(this.pointer, STRING(op))
2803 }
2804
2805 beginImplicitOperation() {
2806 libmupdf._wasm_pdf_begin_implicit_operation(this.pointer)
2807 }
2808
2809 endOperation() {
2810 libmupdf._wasm_pdf_end_operation(this.pointer)
2811 }
2812
2813 abandonOperation() {
2814 libmupdf._wasm_pdf_abandon_operation(this.pointer)
2815 }
2816
2817 canUndo() {
2818 return !!libmupdf._wasm_pdf_can_undo(this.pointer)
2819 }
2820
2821 canRedo() {
2822 return !!libmupdf._wasm_pdf_can_redo(this.pointer)
2823 }
2824
2825 undo() {
2826 libmupdf._wasm_pdf_undo(this.pointer)
2827 }
2828
2829 redo() {
2830 libmupdf._wasm_pdf_redo(this.pointer)
2831 }
2832
2833 isJSSupported() {
2834 return !!libmupdf._wasm_pdf_js_supported(this.pointer)
2835 }
2836
2837 enableJS() {
2838 libmupdf._wasm_pdf_enable_js(this.pointer)
2839 }
2840
2841 disableJS() {
2842 libmupdf._wasm_pdf_disable_js(this.pointer)
2843 }
2844
2845 setJSEventListener(_listener: any) {
2846 throw "TODO"
2847 }
2848
2849 rearrangePages(pages: number[]) {
2850 let n = pages.length
2851 let ptr = Malloc<"int">(n << 2)
2852 for (let i = 0; i < n; ++i)
2853 libmupdf.HEAPU32[(ptr >> 2) + i] = pages[i] || 0
2854 try {
2855 libmupdf._wasm_pdf_rearrange_pages(this.pointer, n, ptr)
2856 } finally {
2857 Free(ptr)
2858 }
2859 }
2860
2861 subsetFonts() {
2862 libmupdf._wasm_pdf_subset_fonts(this.pointer)
2863 }
2864
2865 bake(bakeAnnots = true, bakeWidgets = true) {
2866 libmupdf._wasm_pdf_bake_document(this.pointer, bakeAnnots, bakeWidgets)
2867 }
2868
2869 countLayerConfigs(): number {
2870 return libmupdf._wasm_pdf_count_layer_configs(this.pointer)
2871 }
2872
2873 getLayerConfigCreator(config: number): string {
2874 return fromString(libmupdf._wasm_pdf_layer_config_creator(this.pointer, config))
2875 }
2876
2877 getLayerConfigName(config: number): string {
2878 return fromString(libmupdf._wasm_pdf_layer_config_name(this.pointer, config))
2879 }
2880
2881 selectLayerConfig(config: number) {
2882 libmupdf._wasm_pdf_select_layer_config(this.pointer, config)
2883 }
2884
2885 countLayerConfigUIs(): number {
2886 return libmupdf._wasm_pdf_count_layer_config_uis(this.pointer)
2887 }
2888
2889 getLayerConfigUIInfo(configui: number) {
2890 return fromLayerConfigUIInfo(libmupdf._wasm_pdf_layer_config_ui_info(this.pointer, configui));
2891 }
2892
2893 countLayers(): number {
2894 return libmupdf._wasm_pdf_count_layers(this.pointer)
2895 }
2896
2897 isLayerVisible(layer: number): boolean {
2898 return !!libmupdf._wasm_pdf_layer_is_enabled(this.pointer, layer)
2899 }
2900
2901 setLayerVisible(layer: number, visible: boolean): void {
2902 libmupdf._wasm_pdf_enable_layer(this.pointer, layer, Number(visible))
2903 }
2904
2905 getLayerName(layer: number): string {
2906 return fromString(libmupdf._wasm_pdf_layer_name(this.pointer, layer))
2907 }
2908
2909 resetForm(fields: PDFObject, exclude: boolean) {
2910 libmupdf._wasm_pdf_reset_form(this.pointer, this._PDFOBJ(fields), Number(exclude))
2911 }
2912 }
2913
2914 export class PDFPage extends Page {
2915 _doc: PDFDocument
2916 _annots: PDFAnnotation[] | null
2917 _widgets: PDFWidget[] | null
2918
2919 // PRIVATE
2920 constructor(doc: PDFDocument, pointer: Pointer<"any_page">) {
2921 super(pointer)
2922 this._doc = doc
2923 this._annots = null
2924 this._widgets = null
2925 }
2926
2927 getObject() {
2928 return this._doc._fromPDFObjectKeep(libmupdf._wasm_pdf_page_get_obj(this.pointer))
2929 }
2930
2931 getTransform() {
2932 return fromMatrix(libmupdf._wasm_pdf_page_transform(this.pointer))
2933 }
2934
2935 setPageBox(box: PageBox, rect: Rect) {
2936 let box_ix = ENUM<PageBox>(box, Page.BOXES)
2937 checkRect(rect)
2938 libmupdf._wasm_pdf_set_page_box(this.pointer, box_ix, RECT(rect))
2939 }
2940
2941 override toPixmap(matrix: Matrix, colorspace: ColorSpace, alpha = false, showExtras = true, usage = "View", box: PageBox = "CropBox") {
2942 checkMatrix(matrix)
2943 checkType(colorspace, ColorSpace)
2944 let box_ix = ENUM<PageBox>(box, Page.BOXES)
2945 let result
2946 if (showExtras)
2947 result = libmupdf._wasm_pdf_new_pixmap_from_page_with_usage(this.pointer,
2948 MATRIX(matrix),
2949 colorspace.pointer,
2950 alpha,
2951 STRING(usage),
2952 box_ix)
2953 else
2954 result = libmupdf._wasm_pdf_new_pixmap_from_page_contents_with_usage(this.pointer,
2955 MATRIX(matrix),
2956 colorspace.pointer,
2957 alpha,
2958 STRING(usage),
2959 box_ix)
2960 return new Pixmap(result)
2961 }
2962
2963 getWidgets() {
2964 if (!this._widgets) {
2965 this._widgets = []
2966 let widget = libmupdf._wasm_pdf_first_widget(this.pointer)
2967 while (widget) {
2968 this._widgets.push(new PDFWidget(this._doc, libmupdf._wasm_pdf_keep_annot(widget)))
2969 widget = libmupdf._wasm_pdf_next_widget(widget)
2970 }
2971 }
2972 return this._widgets
2973 }
2974
2975 getAnnotations() {
2976 if (!this._annots) {
2977 this._annots = []
2978 let annot = libmupdf._wasm_pdf_first_annot(this.pointer)
2979 while (annot) {
2980 this._annots.push(new PDFAnnotation(this._doc, libmupdf._wasm_pdf_keep_annot(annot)))
2981 annot = libmupdf._wasm_pdf_next_annot(annot)
2982 }
2983 }
2984 return this._annots
2985 }
2986
2987 createAnnotation(type: PDFAnnotationType) {
2988 let type_ix = ENUM<PDFAnnotationType>(type, PDFAnnotation.ANNOT_TYPES)
2989 let annot = new PDFAnnotation(this._doc, libmupdf._wasm_pdf_create_annot(this.pointer, type_ix))
2990 if (this._annots)
2991 this._annots.push(annot)
2992 return annot
2993 }
2994
2995 deleteAnnotation(annot: PDFAnnotation) {
2996 checkType(annot, PDFAnnotation)
2997 libmupdf._wasm_pdf_delete_annot(this.pointer, annot.pointer)
2998 if (this._annots) {
2999 let ix = this._annots.indexOf(annot)
3000 if (ix >= 0)
3001 this._annots.splice(ix, 1)
3002 }
3003 }
3004
3005 static readonly REDACT_IMAGE_NONE = 0
3006 static readonly REDACT_IMAGE_REMOVE = 1
3007 static readonly REDACT_IMAGE_PIXELS = 2
3008 static readonly REDACT_IMAGE_UNLESS_INVISIBLE = 3
3009
3010 static readonly REDACT_LINE_ART_NONE = 0
3011 static readonly REDACT_LINE_ART_REMOVE_IF_COVERED = 1
3012 static readonly REDACT_LINE_ART_REMOVE_IF_TOUCHED = 2
3013
3014 static readonly REDACT_TEXT_REMOVE = 0
3015 static readonly REDACT_TEXT_NONE = 1
3016
3017 applyRedactions(black_boxes = true, image_method = 2, line_art_method = 1, text_method = 0) {
3018 libmupdf._wasm_pdf_redact_page(this.pointer, Number(black_boxes), image_method, line_art_method, text_method)
3019 }
3020
3021 update() {
3022 return !!libmupdf._wasm_pdf_update_page(this.pointer)
3023 }
3024 }
3025
3026 type PDFObjectPath = Array<number | string | PDFObject>
3027
3028 export class PDFObject extends Userdata<"pdf_obj"> {
3029 static override readonly _drop = libmupdf._wasm_pdf_drop_obj
3030
3031 static readonly Null = new PDFObject(null as unknown as PDFDocument, 0 as Pointer<"pdf_obj">)
3032
3033 _doc: PDFDocument
3034
3035 // PRIVATE
3036 constructor(doc: PDFDocument, pointer: Pointer<"pdf_obj">) {
3037 super(libmupdf._wasm_pdf_keep_obj(pointer))
3038 this._doc = doc
3039 }
3040
3041 isNull() { return this === PDFObject.Null }
3042 isIndirect() { return !!libmupdf._wasm_pdf_is_indirect(this.pointer) }
3043 isBoolean() { return !!libmupdf._wasm_pdf_is_bool(this.pointer) }
3044 isInteger() { return !!libmupdf._wasm_pdf_is_int(this.pointer) }
3045 isReal() { return !!libmupdf._wasm_pdf_is_real(this.pointer) }
3046 isNumber() { return !!libmupdf._wasm_pdf_is_number(this.pointer) }
3047 isName() { return !!libmupdf._wasm_pdf_is_name(this.pointer) }
3048 isString() { return !!libmupdf._wasm_pdf_is_string(this.pointer) }
3049 isArray() { return !!libmupdf._wasm_pdf_is_array(this.pointer) }
3050 isDictionary() { return !!libmupdf._wasm_pdf_is_dict(this.pointer) }
3051 isStream() { return !!libmupdf._wasm_pdf_is_stream(this.pointer) }
3052
3053 asIndirect(): number { return libmupdf._wasm_pdf_to_num(this.pointer) }
3054 asBoolean() { return !!libmupdf._wasm_pdf_to_bool(this.pointer) }
3055 asNumber(): number { return libmupdf._wasm_pdf_to_real(this.pointer) }
3056 asName() { return fromString(libmupdf._wasm_pdf_to_name(this.pointer)) }
3057 asString() { return fromString(libmupdf._wasm_pdf_to_text_string(this.pointer)) }
3058
3059 asByteString() {
3060 let ptr = libmupdf._wasm_pdf_to_string(this.pointer, _wasm_int)
3061 let len = libmupdf.HEAPU32[_wasm_int >> 2] as number
3062 return libmupdf.HEAPU8.slice(ptr, ptr + len)
3063 }
3064
3065 readStream() { return new Buffer(libmupdf._wasm_pdf_load_stream(this.pointer)) }
3066 readRawStream() { return new Buffer(libmupdf._wasm_pdf_load_raw_stream(this.pointer)) }
3067
3068 writeObject(obj: any) {
3069 if (!this.isIndirect())
3070 throw new TypeError("can only call PDFObject.writeObject on an indirect reference")
3071 libmupdf._wasm_pdf_update_object(this._doc.pointer, this.asIndirect(), this._doc._PDFOBJ(obj))
3072 }
3073
3074 writeStream(buf: AnyBuffer) {
3075 if (!this.isIndirect())
3076 throw new TypeError("can only call PDFObject.writeStream on an indirect reference")
3077 libmupdf._wasm_pdf_update_stream(this._doc.pointer, this.pointer, BUFFER(buf), 0)
3078 }
3079
3080 writeRawStream(buf: AnyBuffer) {
3081 if (!this.isIndirect())
3082 throw new TypeError("can only call PDFObject.writeRawStream on an indirect reference")
3083 libmupdf._wasm_pdf_update_stream(this._doc.pointer, this.pointer, BUFFER(buf), 1)
3084 }
3085
3086 resolve() {
3087 return this._doc._fromPDFObjectKeep(libmupdf._wasm_pdf_resolve_indirect(this.pointer))
3088 }
3089
3090 get length() {
3091 return libmupdf._wasm_pdf_array_len(this.pointer)
3092 }
3093
3094 set length(_: number) {
3095 throw new TypeError("object length is read-only")
3096 }
3097
3098 _get(path: PDFObjectPath) {
3099 let obj = this.pointer
3100 for (let key of path) {
3101 if (typeof key === "number")
3102 obj = libmupdf._wasm_pdf_array_get(obj, key)
3103 else if (key instanceof PDFObject)
3104 obj = libmupdf._wasm_pdf_dict_get(obj, key.pointer)
3105 else
3106 obj = libmupdf._wasm_pdf_dict_gets(obj, STRING(key))
3107 if (obj === 0)
3108 break
3109 }
3110 return obj
3111 }
3112
3113 get(...path: PDFObjectPath): PDFObject {
3114 return this._doc._fromPDFObjectKeep(this._get(path))
3115 }
3116
3117 getInheritable(key: string | PDFObject) {
3118 if (key instanceof PDFObject)
3119 return this._doc._fromPDFObjectKeep(libmupdf._wasm_pdf_dict_get_inheritable(this.pointer, key.pointer))
3120 return this._doc._fromPDFObjectKeep(libmupdf._wasm_pdf_dict_gets_inheritable(this.pointer, STRING(key)))
3121 }
3122
3123 put(key: number | string | PDFObject, value: any) {
3124 value = this._doc._toPDFObject(value)
3125 if (typeof key === "number")
3126 libmupdf._wasm_pdf_array_put(this.pointer, key, value.pointer)
3127 else if (key instanceof PDFObject)
3128 libmupdf._wasm_pdf_dict_put(this.pointer, key.pointer, value.pointer)
3129 else
3130 libmupdf._wasm_pdf_dict_puts(this.pointer, STRING(key), value.pointer)
3131 return value
3132 }
3133
3134 push(value: any) {
3135 value = this._doc._toPDFObject(value)
3136 libmupdf._wasm_pdf_array_push(this.pointer, value.pointer)
3137 return value
3138 }
3139
3140 delete(key: number | string | PDFObject) {
3141 if (typeof key === "number")
3142 libmupdf._wasm_pdf_array_delete(this.pointer, key)
3143 else if (key instanceof PDFObject)
3144 libmupdf._wasm_pdf_dict_del(this.pointer, key.pointer)
3145 else
3146 libmupdf._wasm_pdf_dict_dels(this.pointer, STRING(key))
3147 }
3148
3149 override valueOf() {
3150 if (this.isNull()) return null
3151 if (this.isBoolean()) return this.asBoolean()
3152 if (this.isNumber()) return this.asNumber()
3153 if (this.isName()) return this.asName()
3154 if (this.isString()) return this.asString()
3155 if (this.isIndirect()) return `${this.asIndirect()} 0 R`
3156 return this
3157 }
3158
3159 override toString(tight = true, ascii = true) {
3160 return fromStringFree(libmupdf._wasm_pdf_sprint_obj(this.pointer, tight, ascii))
3161 }
3162
3163 forEach(fn: (val: PDFObject, key: number | string, self: PDFObject) => void) {
3164 if (this.isArray()) {
3165 let n = this.length
3166 for (let i = 0; i < n; ++i)
3167 fn(this.get(i), i, this)
3168 } else if (this.isDictionary()) {
3169 let n = libmupdf._wasm_pdf_dict_len(this.pointer)
3170 for (let i = 0; i < n; ++i) {
3171 let key = this._doc._fromPDFObjectKeep(libmupdf._wasm_pdf_dict_get_key(this.pointer, i))
3172 let val = this._doc._fromPDFObjectKeep(libmupdf._wasm_pdf_dict_get_val(this.pointer, i))
3173 fn(val, key.asName(), this)
3174 }
3175 }
3176 }
3177
3178 // Convert to plain Javascript values, objects, and arrays.
3179 // If you want to resolve indirect references, pass an empty object or array as the first argument.
3180 // On exit, this object will contain all indirect objects encountered indexed by object number.
3181 // Note: This function will omit cyclic references.
3182 asJS(seen?: Record<number,PDFObject>): any {
3183 if (this.isIndirect()) {
3184 let ref = this.asIndirect()
3185 if (!seen)
3186 return `${ref} 0 R`
3187 if (ref in seen)
3188 return seen[ref]
3189 seen[ref] = PDFObject.Null // stop recursion!
3190 return seen[ref] = this.resolve().asJS(seen)
3191 }
3192
3193 if (this.isArray()) {
3194 let result: any[] = []
3195 this.forEach(val => {
3196 result.push(val.asJS(seen))
3197 })
3198 return result
3199 }
3200
3201 if (this.isDictionary()) {
3202 let result: Record<string,any> = {}
3203 this.forEach((val, key) => {
3204 result[key] = val.asJS(seen)
3205 })
3206 return result
3207 }
3208
3209 return this.valueOf()
3210 }
3211 }
3212
3213 export class PDFGraftMap extends Userdata<"pdf_graft_map"> {
3214 static override readonly _drop = libmupdf._wasm_pdf_drop_graft_map
3215
3216 _doc: PDFDocument
3217
3218 // PRIVATE
3219 constructor(doc: PDFDocument, pointer: Pointer<"pdf_graft_map">) {
3220 super(pointer)
3221 this._doc = doc
3222 }
3223
3224 graftObject(obj: PDFObject) {
3225 checkType(obj, PDFObject)
3226 return this._doc._fromPDFObjectNew(libmupdf._wasm_pdf_graft_mapped_object(this.pointer, obj.pointer))
3227 }
3228
3229 graftPage(to: number, srcDoc: PDFDocument, srcPage: number) {
3230 checkType(to, "number")
3231 checkType(srcDoc, PDFDocument)
3232 checkType(srcPage, "number")
3233 libmupdf._wasm_pdf_graft_mapped_page(this.pointer, to, srcDoc.pointer, srcPage)
3234 }
3235 }
3236
3237 export type PDFAnnotationType =
3238 "Text" |
3239 "Link" |
3240 "FreeText" |
3241 "Line" |
3242 "Square" |
3243 "Circle" |
3244 "Polygon" |
3245 "PolyLine" |
3246 "Highlight" |
3247 "Underline" |
3248 "Squiggly" |
3249 "StrikeOut" |
3250 "Redact" |
3251 "Stamp" |
3252 "Caret" |
3253 "Ink" |
3254 "Popup" |
3255 "FileAttachment" |
3256 "Sound" |
3257 "Movie" |
3258 "RichMedia" |
3259 "Widget" |
3260 "Screen" |
3261 "PrinterMark" |
3262 "TrapNet" |
3263 "Watermark" |
3264 "3D" |
3265 "Projection"
3266
3267 export type PDFAnnotationLineEndingStyle =
3268 "None" |
3269 "Square" |
3270 "Circle" |
3271 "Diamond" |
3272 "OpenArrow" |
3273 "ClosedArrow" |
3274 "Butt" |
3275 "ROpenArrow" |
3276 "RClosedArrow" |
3277 "Slash"
3278
3279 export type PDFAnnotationBorderStyle = "Solid" | "Dashed" | "Beveled" | "Inset" | "Underline"
3280
3281 export type PDFAnnotationBorderEffect = "None" | "Cloudy"
3282
3283 export type PDFAnnotationIntent =
3284 null |
3285 "FreeTextCallout" |
3286 "FreeTextTypeWriter" |
3287 "LineArrow" |
3288 "LineDimension" |
3289 "PloyLine" |
3290 "PolygonCloud" |
3291 "PolygonDimension" |
3292 "StampImage" |
3293 "StampSnapshot"
3294
3295 export class PDFAnnotation extends Userdata<"pdf_annot"> {
3296 static override readonly _drop = libmupdf._wasm_pdf_drop_annot
3297
3298 _doc: PDFDocument
3299
3300 /* IMPORTANT: Keep in sync with mupdf/pdf/annot.h and PDFAnnotation.java */
3301 static readonly ANNOT_TYPES: PDFAnnotationType[] = [
3302 "Text",
3303 "Link",
3304 "FreeText",
3305 "Line",
3306 "Square",
3307 "Circle",
3308 "Polygon",
3309 "PolyLine",
3310 "Highlight",
3311 "Underline",
3312 "Squiggly",
3313 "StrikeOut",
3314 "Redact",
3315 "Stamp",
3316 "Caret",
3317 "Ink",
3318 "Popup",
3319 "FileAttachment",
3320 "Sound",
3321 "Movie",
3322 "RichMedia",
3323 "Widget",
3324 "Screen",
3325 "PrinterMark",
3326 "TrapNet",
3327 "Watermark",
3328 "3D",
3329 "Projection",
3330 ]
3331
3332 static readonly LINE_ENDING: PDFAnnotationLineEndingStyle[] = [
3333 "None",
3334 "Square",
3335 "Circle",
3336 "Diamond",
3337 "OpenArrow",
3338 "ClosedArrow",
3339 "Butt",
3340 "ROpenArrow",
3341 "RClosedArrow",
3342 "Slash",
3343 ]
3344
3345 static readonly BORDER_STYLE: PDFAnnotationBorderStyle[] = [ "Solid", "Dashed", "Beveled", "Inset", "Underline" ]
3346
3347 static readonly BORDER_EFFECT: PDFAnnotationBorderEffect[] = [ "None", "Cloudy" ]
3348
3349 static readonly INTENT: PDFAnnotationIntent[] = [
3350 null,
3351 "FreeTextCallout",
3352 "FreeTextTypeWriter",
3353 "LineArrow",
3354 "LineDimension",
3355 "PloyLine",
3356 "PolygonCloud",
3357 "PolygonDimension",
3358 "StampImage",
3359 "StampSnapshot"
3360 ]
3361
3362 // Bit masks for getFlags and setFlags
3363 static readonly IS_INVISIBLE = 1 << (1 - 1)
3364 static readonly IS_HIDDEN = 1 << (2 - 1)
3365 static readonly IS_PRINT = 1 << (3 - 1)
3366 static readonly IS_NO_ZOOM = 1 << (4 - 1)
3367 static readonly IS_NO_ROTATE = 1 << (5 - 1)
3368 static readonly IS_NO_VIEW = 1 << (6 - 1)
3369 static readonly IS_READ_ONLY = 1 << (7 - 1)
3370 static readonly IS_LOCKED = 1 << (8 - 1)
3371 static readonly IS_TOGGLE_NO_VIEW = 1 << (9 - 1)
3372 static readonly IS_LOCKED_CONTENTS = 1 << (10 - 1)
3373
3374 // PRIVATE
3375 constructor(doc: PDFDocument, pointer: Pointer<"pdf_annot">) {
3376 super(pointer)
3377 this._doc = doc
3378 }
3379
3380 getObject() {
3381 return this._doc._fromPDFObjectKeep(libmupdf._wasm_pdf_annot_obj(this.pointer))
3382 }
3383
3384 getBounds() {
3385 return fromRect(libmupdf._wasm_pdf_bound_annot(this.pointer))
3386 }
3387
3388 run(device: Device, matrix: Matrix) {
3389 checkType(device, Device)
3390 checkMatrix(matrix)
3391 libmupdf._wasm_pdf_run_annot(this.pointer, device.pointer, MATRIX(matrix))
3392 }
3393
3394 toPixmap(matrix: Matrix, colorspace: ColorSpace, alpha = false) {
3395 checkMatrix(matrix)
3396 checkType(colorspace, ColorSpace)
3397 return new Pixmap(
3398 libmupdf._wasm_pdf_new_pixmap_from_annot(
3399 this.pointer,
3400 MATRIX(matrix),
3401 colorspace.pointer,
3402 alpha)
3403 )
3404 }
3405
3406 toDisplayList() {
3407 return new DisplayList(libmupdf._wasm_pdf_new_display_list_from_annot(this.pointer))
3408 }
3409
3410 update() {
3411 return !!libmupdf._wasm_pdf_update_annot(this.pointer)
3412 }
3413
3414 getType() {
3415 let type = libmupdf._wasm_pdf_annot_type(this.pointer)
3416 return PDFAnnotation.ANNOT_TYPES[type] || "Text"
3417 }
3418
3419 getLanguage() {
3420 return fromStringOrNull(libmupdf._wasm_pdf_annot_language(this.pointer))
3421 }
3422
3423 setLanguage(lang: string) {
3424 libmupdf._wasm_pdf_set_annot_language(this.pointer, STRING(lang))
3425 }
3426
3427 getFlags() {
3428 return libmupdf._wasm_pdf_annot_flags(this.pointer)
3429 }
3430
3431 setFlags(flags: number) {
3432 return libmupdf._wasm_pdf_set_annot_flags(this.pointer, flags)
3433 }
3434
3435 getContents() {
3436 return fromString(libmupdf._wasm_pdf_annot_contents(this.pointer))
3437 }
3438
3439 setContents(text: string) {
3440 libmupdf._wasm_pdf_set_annot_contents(this.pointer, STRING(text))
3441 }
3442
3443 getAuthor() {
3444 return fromString(libmupdf._wasm_pdf_annot_author(this.pointer))
3445 }
3446
3447 setAuthor(text: string) {
3448 libmupdf._wasm_pdf_set_annot_author(this.pointer, STRING(text))
3449 }
3450
3451 getCreationDate() {
3452 return new Date(libmupdf._wasm_pdf_annot_creation_date(this.pointer) * 1000)
3453 }
3454
3455 setCreationDate(date: Date) {
3456 checkType(date, Date)
3457 libmupdf._wasm_pdf_set_annot_creation_date(this.pointer, date.getTime() / 1000)
3458 }
3459
3460 getModificationDate() {
3461 return new Date(libmupdf._wasm_pdf_annot_modification_date(this.pointer) * 1000)
3462 }
3463
3464 setModificationDate(date: Date) {
3465 checkType(date, Date)
3466 libmupdf._wasm_pdf_set_annot_modification_date(this.pointer, date.getTime() / 1000)
3467 }
3468
3469 hasRect() {
3470 return !!libmupdf._wasm_pdf_annot_has_rect(this.pointer)
3471 }
3472 hasInkList() {
3473 return !!libmupdf._wasm_pdf_annot_has_ink_list(this.pointer)
3474 }
3475 hasQuadPoints() {
3476 return !!libmupdf._wasm_pdf_annot_has_quad_points(this.pointer)
3477 }
3478 hasVertices() {
3479 return !!libmupdf._wasm_pdf_annot_has_vertices(this.pointer)
3480 }
3481 hasLine() {
3482 return !!libmupdf._wasm_pdf_annot_has_line(this.pointer)
3483 }
3484 hasInteriorColor() {
3485 return !!libmupdf._wasm_pdf_annot_has_interior_color(this.pointer)
3486 }
3487 hasLineEndingStyles() {
3488 return !!libmupdf._wasm_pdf_annot_has_line_ending_styles(this.pointer)
3489 }
3490 hasBorder() {
3491 return !!libmupdf._wasm_pdf_annot_has_border(this.pointer)
3492 }
3493 hasBorderEffect() {
3494 return !!libmupdf._wasm_pdf_annot_has_border_effect(this.pointer)
3495 }
3496 hasIcon() {
3497 return !!libmupdf._wasm_pdf_annot_has_icon_name(this.pointer)
3498 }
3499 hasOpen() {
3500 return !!libmupdf._wasm_pdf_annot_has_open(this.pointer)
3501 }
3502 hasAuthor() {
3503 return !!libmupdf._wasm_pdf_annot_has_author(this.pointer)
3504 }
3505 hasFilespec() {
3506 return !!libmupdf._wasm_pdf_annot_has_filespec(this.pointer)
3507 }
3508 hasCallout() {
3509 return !!libmupdf._wasm_pdf_annot_has_callout(this.pointer)
3510 }
3511 hasRichContents() {
3512 return !!libmupdf._wasm_pdf_annot_has_rich_contents(this.pointer)
3513 }
3514
3515 getRect() {
3516 return fromRect(libmupdf._wasm_pdf_annot_rect(this.pointer))
3517 }
3518
3519 setRect(rect: Rect) {
3520 checkRect(rect)
3521 libmupdf._wasm_pdf_set_annot_rect(this.pointer, RECT(rect))
3522 }
3523
3524 getPopup() {
3525 return fromRect(libmupdf._wasm_pdf_annot_popup(this.pointer))
3526 }
3527
3528 setPopup(rect: Rect) {
3529 checkRect(rect)
3530 libmupdf._wasm_pdf_set_annot_popup(this.pointer, RECT(rect))
3531 }
3532
3533 getIsOpen() {
3534 return !!libmupdf._wasm_pdf_annot_is_open(this.pointer)
3535 }
3536
3537 setIsOpen(isOpen: boolean) {
3538 checkType(isOpen, "boolean")
3539 libmupdf._wasm_pdf_set_annot_is_open(this.pointer, isOpen)
3540 }
3541
3542 getHiddenForEditing() {
3543 return !!libmupdf._wasm_pdf_annot_hidden_for_editing(this.pointer)
3544 }
3545
3546 setHiddenForEditing(isHidden: boolean) {
3547 checkType(isHidden, "boolean")
3548 libmupdf._wasm_pdf_set_annot_hidden_for_editing(this.pointer, isHidden)
3549 }
3550
3551 getIcon() {
3552 return fromString(libmupdf._wasm_pdf_annot_icon_name(this.pointer))
3553 }
3554
3555 setIcon(text: string) {
3556 checkType(text, "string")
3557 libmupdf._wasm_pdf_set_annot_icon_name(this.pointer, STRING(text))
3558 }
3559
3560 getOpacity() {
3561 return libmupdf._wasm_pdf_annot_opacity(this.pointer)
3562 }
3563
3564 setOpacity(opacity: number) {
3565 checkType(opacity, "number")
3566 libmupdf._wasm_pdf_set_annot_opacity(this.pointer, opacity)
3567 }
3568
3569 getQuadding() {
3570 return libmupdf._wasm_pdf_annot_quadding(this.pointer)
3571 }
3572
3573 setQuadding(quadding: number) {
3574 checkType(quadding, "number")
3575 libmupdf._wasm_pdf_set_annot_quadding(this.pointer, quadding)
3576 }
3577
3578 getLine() {
3579 let a = fromPoint(libmupdf._wasm_pdf_annot_line_1(this.pointer))
3580 let b = fromPoint(libmupdf._wasm_pdf_annot_line_2(this.pointer))
3581 return [ a, b ]
3582 }
3583
3584 setLine(a: Point, b: Point) {
3585 checkPoint(a)
3586 checkPoint(b)
3587 libmupdf._wasm_pdf_set_annot_line(this.pointer, POINT(a), POINT2(b))
3588 }
3589
3590 getLineEndingStyles() {
3591 let a = libmupdf._wasm_pdf_annot_line_ending_styles_start(this.pointer)
3592 let b = libmupdf._wasm_pdf_annot_line_ending_styles_end(this.pointer)
3593 return {
3594 start: PDFAnnotation.LINE_ENDING[a] || "None",
3595 end: PDFAnnotation.LINE_ENDING[b] || "None",
3596 }
3597 }
3598
3599 setLineEndingStyles(start: PDFAnnotationLineEndingStyle, end: PDFAnnotationLineEndingStyle) {
3600 let start_ix = ENUM<PDFAnnotationLineEndingStyle>(start, PDFAnnotation.LINE_ENDING)
3601 let end_ix = ENUM<PDFAnnotationLineEndingStyle>(end, PDFAnnotation.LINE_ENDING)
3602 libmupdf._wasm_pdf_set_annot_line_ending_styles(this.pointer, start_ix, end_ix)
3603 }
3604
3605 getLineCaption() {
3606 return libmupdf._wasm_pdf_annot_line_caption(this.pointer)
3607 }
3608
3609 setLineCaption(on: boolean) {
3610 return libmupdf._wasm_pdf_set_annot_line_caption(this.pointer, on)
3611 }
3612
3613 getLineCaptionOffset() {
3614 return fromPoint(libmupdf._wasm_pdf_annot_line_caption_offset(this.pointer))
3615 }
3616
3617 setLineCaptionOffset(p: Point) {
3618 return libmupdf._wasm_pdf_set_annot_line_caption_offset(this.pointer, POINT(p))
3619 }
3620
3621 getLineLeader() {
3622 return libmupdf._wasm_pdf_annot_line_leader(this.pointer)
3623 }
3624
3625 getLineLeaderExtension() {
3626 return libmupdf._wasm_pdf_annot_line_leader_extension(this.pointer)
3627 }
3628
3629 getLineLeaderOffset() {
3630 return libmupdf._wasm_pdf_annot_line_leader_offset(this.pointer)
3631 }
3632
3633 setLineLeader(v: number) {
3634 return libmupdf._wasm_pdf_set_annot_line_leader(this.pointer, v)
3635 }
3636
3637 setLineLeaderExtension(v: number) {
3638 return libmupdf._wasm_pdf_set_annot_line_leader_extension(this.pointer, v)
3639 }
3640
3641 setLineLeaderOffset(v: number) {
3642 return libmupdf._wasm_pdf_set_annot_line_leader_offset(this.pointer, v)
3643 }
3644
3645 getCalloutStyle() {
3646 let style = libmupdf._wasm_pdf_annot_callout_style(this.pointer)
3647 return PDFAnnotation.LINE_ENDING[style] || "None"
3648 }
3649
3650 setCalloutStyle(style: PDFAnnotationLineEndingStyle) {
3651 let style_ix = ENUM<PDFAnnotationLineEndingStyle>(style, PDFAnnotation.LINE_ENDING)
3652 libmupdf._wasm_pdf_set_annot_callout_style(this.pointer, style_ix)
3653 }
3654
3655 getCalloutLine() {
3656 let n = libmupdf._wasm_pdf_annot_callout_line(this.pointer,
3657 (_wasm_point << 2) as Pointer<"fz_point">)
3658 if (n == 3)
3659 return [
3660 fromPoint((_wasm_point+0) << 2 as Pointer<"fz_point">),
3661 fromPoint((_wasm_point+1) << 2 as Pointer<"fz_point">),
3662 fromPoint((_wasm_point+2) << 2 as Pointer<"fz_point">)
3663 ]
3664 if (n == 2)
3665 return [
3666 fromPoint((_wasm_point+0) << 2 as Pointer<"fz_point">),
3667 fromPoint((_wasm_point+1) << 2 as Pointer<"fz_point">)
3668 ]
3669 return null
3670 }
3671
3672 setCalloutLine(line: Point[]) {
3673 let a = line[0] || [0, 0]
3674 let b = line[1] || [0, 0]
3675 let c = line[2] || [0, 0]
3676 libmupdf._wasm_pdf_set_annot_callout_line(this.pointer, line.length, POINT(a), POINT2(b), POINT3(c))
3677 }
3678
3679 getCalloutPoint() {
3680 let line = this.getCalloutLine()
3681 if (line)
3682 return line[0]
3683 return undefined
3684 }
3685
3686 setCalloutPoint(p: Point) {
3687 libmupdf._wasm_pdf_set_annot_callout_point(this.pointer, POINT(p))
3688 }
3689
3690 getColor() {
3691 return fromAnnotColor(libmupdf._wasm_pdf_annot_color(this.pointer, COLOR()))
3692 }
3693
3694 getInteriorColor() {
3695 return fromAnnotColor(libmupdf._wasm_pdf_annot_interior_color(this.pointer, COLOR()))
3696 }
3697
3698 setColor(color: AnnotColor) {
3699 checkAnnotColor(color)
3700 libmupdf._wasm_pdf_set_annot_color(this.pointer, color.length, COLOR(color))
3701 }
3702
3703 setInteriorColor(color: AnnotColor) {
3704 checkAnnotColor(color)
3705 libmupdf._wasm_pdf_set_annot_interior_color(this.pointer, color.length, COLOR(color))
3706 }
3707
3708 getBorderWidth() {
3709 return libmupdf._wasm_pdf_annot_border_width(this.pointer)
3710 }
3711
3712 setBorderWidth(value: number) {
3713 checkType(value, "number")
3714 return libmupdf._wasm_pdf_set_annot_border_width(this.pointer, value)
3715 }
3716
3717 getBorderStyle() {
3718 return PDFAnnotation.BORDER_STYLE[libmupdf._wasm_pdf_annot_border_style(this.pointer)] || "Solid"
3719 }
3720
3721 setBorderStyle(value: PDFAnnotationBorderStyle) {
3722 let value_ix = ENUM<PDFAnnotationBorderStyle>(value, PDFAnnotation.BORDER_STYLE)
3723 return libmupdf._wasm_pdf_set_annot_border_style(this.pointer, value_ix)
3724 }
3725
3726 getBorderEffect() {
3727 return PDFAnnotation.BORDER_EFFECT[libmupdf._wasm_pdf_annot_border_effect(this.pointer)] || "None"
3728 }
3729
3730 setBorderEffect(value: PDFAnnotationBorderEffect) {
3731 let value_ix = ENUM<PDFAnnotationBorderEffect>(value, PDFAnnotation.BORDER_EFFECT)
3732 return libmupdf._wasm_pdf_set_annot_border_effect(this.pointer, value_ix)
3733 }
3734
3735 getBorderEffectIntensity() {
3736 return libmupdf._wasm_pdf_annot_border_effect_intensity(this.pointer)
3737 }
3738
3739 setBorderEffectIntensity(value: number) {
3740 checkType(value, "number")
3741 return libmupdf._wasm_pdf_set_annot_border_effect_intensity(this.pointer, value)
3742 }
3743
3744 getBorderDashCount() {
3745 return libmupdf._wasm_pdf_annot_border_dash_count(this.pointer)
3746 }
3747
3748 getBorderDashItem(idx: number) {
3749 return libmupdf._wasm_pdf_annot_border_dash_item(this.pointer, idx)
3750 }
3751
3752 clearBorderDash() {
3753 libmupdf._wasm_pdf_clear_annot_border_dash(this.pointer)
3754 }
3755
3756 addBorderDashItem(v: number) {
3757 checkType(v, "number")
3758 return libmupdf._wasm_pdf_add_annot_border_dash_item(this.pointer, v)
3759 }
3760
3761 getBorderDashPattern() {
3762 let n = this.getBorderDashCount()
3763 let result = new Array(n)
3764 for (let i = 0; i < n; ++i)
3765 result[i] = this.getBorderDashItem(i)
3766 return result
3767 }
3768
3769 setBorderDashPattern(list: number[]) {
3770 this.clearBorderDash()
3771 for (let v of list)
3772 this.addBorderDashItem(v)
3773 }
3774
3775 getIntent(): PDFAnnotationIntent {
3776 return PDFAnnotation.INTENT[libmupdf._wasm_pdf_annot_intent(this.pointer)] || null
3777 }
3778
3779 setIntent(value: PDFAnnotationIntent) {
3780 let value_ix = ENUM<PDFAnnotationIntent>(value, PDFAnnotation.INTENT)
3781 return libmupdf._wasm_pdf_set_annot_intent(this.pointer, value_ix)
3782 }
3783
3784 setDefaultAppearance(fontName: string, size: number, color: AnnotColor) {
3785 checkType(fontName, "string")
3786 checkType(size, "number")
3787 checkAnnotColor(color)
3788 libmupdf._wasm_pdf_set_annot_default_appearance(this.pointer, STRING(fontName), size, color.length, COLOR(color))
3789 }
3790
3791 getDefaultAppearance() {
3792 let font = fromString(libmupdf._wasm_pdf_annot_default_appearance_font(this.pointer))
3793 let size = libmupdf._wasm_pdf_annot_default_appearance_size(this.pointer)
3794 let color = fromAnnotColor(libmupdf._wasm_pdf_annot_default_appearance_color(this.pointer, COLOR()))
3795 return { font, size, color }
3796 }
3797
3798 getFileSpec() {
3799 return this._doc._fromPDFObjectKeep(libmupdf._wasm_pdf_annot_filespec(this.pointer))
3800 }
3801
3802 setFileSpec(fs: PDFObject) {
3803 return libmupdf._wasm_pdf_set_annot_filespec(this.pointer, this._doc._PDFOBJ(fs))
3804 }
3805
3806 getQuadPoints() {
3807 let n = libmupdf._wasm_pdf_annot_quad_point_count(this.pointer)
3808 let result: Quad[] = []
3809 for (let i = 0; i < n; ++i)
3810 result.push(fromQuad(libmupdf._wasm_pdf_annot_quad_point(this.pointer, i)))
3811 return result
3812 }
3813
3814 clearQuadPoints() {
3815 libmupdf._wasm_pdf_clear_annot_quad_points(this.pointer)
3816 }
3817
3818 addQuadPoint(quad: Quad) {
3819 checkQuad(quad)
3820 libmupdf._wasm_pdf_add_annot_quad_point(this.pointer, QUAD(quad))
3821 }
3822
3823 setQuadPoints(quadlist: Quad[]) {
3824 this.clearQuadPoints()
3825 for (let quad of quadlist)
3826 this.addQuadPoint(quad)
3827 }
3828
3829 getVertices() {
3830 let n = libmupdf._wasm_pdf_annot_vertex_count(this.pointer)
3831 let result: Point[] = new Array(n)
3832 for (let i = 0; i < n; ++i)
3833 result[i] = fromPoint(libmupdf._wasm_pdf_annot_vertex(this.pointer, i))
3834 return result
3835 }
3836
3837 clearVertices() {
3838 libmupdf._wasm_pdf_clear_annot_vertices(this.pointer)
3839 }
3840
3841 addVertex(vertex: Point) {
3842 checkPoint(vertex)
3843 libmupdf._wasm_pdf_add_annot_vertex(this.pointer, POINT(vertex))
3844 }
3845
3846 setVertices(vertexlist: Point[]) {
3847 this.clearVertices()
3848 for (let vertex of vertexlist)
3849 this.addVertex(vertex)
3850 }
3851
3852 getInkList() {
3853 let n = libmupdf._wasm_pdf_annot_ink_list_count(this.pointer)
3854 let outer: Point[][] = []
3855 for (let i = 0; i < n; ++i) {
3856 let m = libmupdf._wasm_pdf_annot_ink_list_stroke_count(this.pointer, i)
3857 let inner: Point[] = new Array(m)
3858 for (let k = 0; k < m; ++k)
3859 inner[k] = fromPoint(libmupdf._wasm_pdf_annot_ink_list_stroke_vertex(this.pointer, i, k))
3860 outer.push(inner)
3861 }
3862 return outer
3863 }
3864
3865 clearInkList() {
3866 libmupdf._wasm_pdf_clear_annot_ink_list(this.pointer)
3867 }
3868
3869 addInkListStroke() {
3870 libmupdf._wasm_pdf_add_annot_ink_list_stroke(this.pointer)
3871 }
3872
3873 addInkListStrokeVertex(v: Point) {
3874 checkPoint(v)
3875 libmupdf._wasm_pdf_add_annot_ink_list_stroke_vertex(this.pointer, POINT(v))
3876 }
3877
3878 setInkList(inklist: Point[][]) {
3879 this.clearInkList()
3880 for (let stroke of inklist) {
3881 this.addInkListStroke()
3882 for (let vertex of stroke)
3883 this.addInkListStrokeVertex(vertex)
3884 }
3885 }
3886
3887 getRichContents() {
3888 return fromString(libmupdf._wasm_pdf_annot_rich_contents(this.pointer))
3889 }
3890
3891 setRichContents(plain: string, html: string) {
3892 checkType(plain, "string")
3893 checkType(html, "string")
3894 libmupdf._wasm_pdf_set_annot_rich_contents(this.pointer, STRING(plain), STRING2(html))
3895 }
3896
3897 getRichDefaults() {
3898 return fromString(libmupdf._wasm_pdf_annot_rich_defaults(this.pointer))
3899 }
3900
3901 setRichDefaults(style: string) {
3902 checkType(style, "string")
3903 libmupdf._wasm_pdf_set_annot_rich_defaults(this.pointer, STRING(style))
3904 }
3905
3906 setStampImage(image: Image) {
3907 libmupdf._wasm_pdf_set_annot_stamp_image(this.pointer, image.pointer)
3908 }
3909
3910 setAppearanceFromDisplayList(appearance: string | null, state: string | null, transform: Matrix, list: DisplayList) {
3911 checkMatrix(transform)
3912 checkType(list, DisplayList)
3913 libmupdf._wasm_pdf_set_annot_appearance_from_display_list(
3914 this.pointer,
3915 STRING_OPT(appearance),
3916 STRING2_OPT(state),
3917 MATRIX(transform),
3918 list.pointer
3919 )
3920 }
3921
3922 setAppearance(appearance: string | null, state: string | null, transform: Matrix, bbox: Rect, resources: any, contents: AnyBuffer) {
3923 checkMatrix(transform)
3924 checkRect(bbox)
3925 libmupdf._wasm_pdf_set_annot_appearance(
3926 this.pointer,
3927 STRING_OPT(appearance),
3928 STRING2_OPT(state),
3929 MATRIX(transform),
3930 RECT(bbox),
3931 this._doc._PDFOBJ(resources),
3932 BUFFER(contents)
3933 )
3934 }
3935
3936 applyRedaction(black_boxes = 1, image_method = 2, line_art_method = 1, text_method = 0) {
3937 libmupdf._wasm_pdf_apply_redaction(this.pointer, black_boxes, image_method, line_art_method, text_method)
3938 }
3939 }
3940
3941 export class PDFWidget extends PDFAnnotation {
3942 /* IMPORTANT: Keep in sync with mupdf/pdf/widget.h and PDFWidget.java */
3943 static readonly WIDGET_TYPES = [
3944 "widget", // unknown
3945 "button",
3946 "checkbox",
3947 "combobox",
3948 "listbox",
3949 "radiobutton",
3950 "signature",
3951 "text",
3952 ]
3953
3954 /* Field flags */
3955 static readonly FIELD_IS_READ_ONLY = 1
3956 static readonly FIELD_IS_REQUIRED = 1 << 1
3957 static readonly FIELD_IS_NO_EXPORT = 1 << 2
3958
3959 /* Text fields */
3960 static readonly TX_FIELD_IS_MULTILINE = 1 << 12
3961 static readonly TX_FIELD_IS_PASSWORD = 1 << 13
3962 static readonly TX_FIELD_IS_COMB = 1 << 24
3963
3964 /* Button fields */
3965 static readonly BTN_FIELD_IS_NO_TOGGLE_TO_OFF = 1 << 14
3966 static readonly BTN_FIELD_IS_RADIO = 1 << 15
3967 static readonly BTN_FIELD_IS_PUSHBUTTON = 1 << 16
3968
3969 /* Choice fields */
3970 static readonly CH_FIELD_IS_COMBO = 1 << 17
3971 static readonly CH_FIELD_IS_EDIT = 1 << 18
3972 static readonly CH_FIELD_IS_SORT = 1 << 19
3973 static readonly CH_FIELD_IS_MULTI_SELECT = 1 << 21
3974
3975 getFieldType() {
3976 return PDFWidget.WIDGET_TYPES[libmupdf._wasm_pdf_annot_field_type(this.pointer)] || "button"
3977 }
3978
3979 isButton() {
3980 let type = this.getFieldType()
3981 return type === "button" || type === "checkbox" || type === "radiobutton"
3982 }
3983
3984 isPushButton() {
3985 return this.getFieldType() === "button"
3986 }
3987
3988 isCheckbox() {
3989 return this.getFieldType() === "checkbox"
3990 }
3991
3992 isRadioButton() {
3993 return this.getFieldType() === "radiobutton"
3994 }
3995
3996 isText() {
3997 return this.getFieldType() === "text"
3998 }
3999
4000 isChoice() {
4001 let type = this.getFieldType()
4002 return type === "combobox" || type === "listbox"
4003 }
4004
4005 isListBox() {
4006 return this.getFieldType() === "listbox"
4007 }
4008
4009 isComboBox() {
4010 return this.getFieldType() === "combobox"
4011 }
4012
4013 getFieldFlags() {
4014 return libmupdf._wasm_pdf_annot_field_flags(this.pointer)
4015 }
4016
4017 isMultiline() {
4018 return (this.getFieldFlags() & PDFWidget.TX_FIELD_IS_MULTILINE) !== 0
4019 }
4020
4021 isPassword() {
4022 return (this.getFieldFlags() & PDFWidget.TX_FIELD_IS_PASSWORD) !== 0
4023 }
4024
4025 isComb() {
4026 return (this.getFieldFlags() & PDFWidget.TX_FIELD_IS_COMB) !== 0
4027 }
4028
4029 isReadOnly() {
4030 return (this.getFieldFlags() & PDFWidget.FIELD_IS_READ_ONLY) !== 0
4031 }
4032
4033 getLabel() {
4034 return fromString(libmupdf._wasm_pdf_annot_field_label(this.pointer))
4035 }
4036
4037 getName() {
4038 return fromStringFree(libmupdf._wasm_pdf_load_field_name(this.pointer))
4039 }
4040
4041 getValue() {
4042 return fromString(libmupdf._wasm_pdf_annot_field_value(this.pointer))
4043 }
4044
4045 setTextValue(value: string) {
4046 return libmupdf._wasm_pdf_set_annot_text_field_value(this.pointer, STRING(value))
4047 }
4048
4049 getMaxLen() {
4050 return libmupdf._wasm_pdf_annot_text_widget_max_len(this.pointer)
4051 }
4052
4053 setChoiceValue(value: string) {
4054 return libmupdf._wasm_pdf_set_annot_choice_field_value(this.pointer, STRING(value))
4055 }
4056
4057 getOptions(isExport=false) {
4058 let result: string[] = []
4059 let n = libmupdf._wasm_pdf_annot_choice_field_option_count(this.pointer)
4060 for (let i = 0; i < n; ++i) {
4061 result.push(
4062 fromString(
4063 libmupdf._wasm_pdf_annot_choice_field_option(this.pointer, isExport, i)
4064 )
4065 )
4066 }
4067 return result
4068 }
4069
4070 toggle() {
4071 return libmupdf._wasm_pdf_toggle_widget(this.pointer)
4072 }
4073
4074 // Interactive Text Widget editing in a GUI.
4075 // TODO: getEditingState()
4076 // TODO: setEditingState()
4077 // TODO: clearEditingState()
4078 // TODO: layoutTextWidget()
4079
4080 // Interactive form validation Javascript triggers.
4081 // NOTE: No embedded PDF Javascript engine in WASM build.
4082 // TODO: eventEnter()
4083 // TODO: eventExit()
4084 // TODO: eventDown()
4085 // TODO: eventUp()
4086 // TODO: eventFocus()
4087 // TODO: eventBlur()
4088
4089 // NOTE: No OpenSSL support in WASM build.
4090 // TODO: isSigned()
4091 // TODO: validateSignature()
4092 // TODO: checkCertificate()
4093 // TODO: checkDigest()
4094 // TODO: getSignature()
4095 // TODO: previewSignature()
4096 // TODO: clearSignature()
4097 // TODO: sign()
4098 }
4099
4100 /* -------------------------------------------------------------------------- */
4101
4102 /* We need a certain level of ugliness to allow callbacks from C to JS */
4103
4104 declare global {
4105 function $libmupdf_stm_close(ptr: number): void
4106 function $libmupdf_stm_seek(ptr: number, pos: number, offset: number, whence: number): number
4107 function $libmupdf_stm_read(ptr: number, pos: number, addr: number, size: number): number
4108 }
4109
4110 interface StreamHandle {
4111 fileSize(): number,
4112 read(memory: Uint8Array, offset: number, length: number, position: number): number,
4113 close(): void,
4114 }
4115
4116 var $libmupdf_stm_id = 0
4117 var $libmupdf_stm_table: Map<number,StreamHandle> = new Map()
4118
4119 globalThis.$libmupdf_stm_close = function (id: number) {
4120 let handle = $libmupdf_stm_table.get(id)
4121 if (handle) {
4122 handle.close()
4123 $libmupdf_stm_table.delete(id)
4124 return
4125 }
4126 throw new Error("invalid file handle")
4127 }
4128
4129 globalThis.$libmupdf_stm_seek = function (id: number, pos: number, offset: number, whence: number) {
4130 let handle = $libmupdf_stm_table.get(id)
4131 if (handle) {
4132 if (whence === 0)
4133 return offset
4134 if (whence === 1)
4135 return pos + offset
4136 if (whence === 2) {
4137 let size = handle.fileSize()
4138 if (size < 0)
4139 return -1
4140 return size + offset
4141 }
4142 throw new Error("invalid whence argument")
4143 }
4144 throw new Error("invalid file handle")
4145 }
4146
4147 globalThis.$libmupdf_stm_read = function (id: number, pos: number, addr: number, size: number) {
4148 let handle = $libmupdf_stm_table.get(id)
4149 if (handle) {
4150 return handle.read(libmupdf.HEAPU8, addr, size, pos)
4151 }
4152 throw new Error("invalid file handle")
4153 }
4154
4155 export class Stream extends Userdata<"fz_stream"> {
4156 static override readonly _drop = libmupdf._wasm_drop_stream
4157 constructor(handle: StreamHandle) {
4158 let id = $libmupdf_stm_id++
4159 $libmupdf_stm_table.set(id, handle)
4160 super(libmupdf._wasm_new_stream(id))
4161 }
4162 }
4163
4164 /* -------------------------------------------------------------------------- */
4165
4166 var $libmupdf_load_font_file_js: (name: string, script: string, bold: boolean, italic: boolean) => Font | null
4167
4168 declare global {
4169 function $libmupdf_load_font_file(name: Pointer<"char">, script: Pointer<"char">, bold: boolean, italic: boolean): Pointer<"fz_font">
4170 }
4171
4172 globalThis.$libmupdf_load_font_file = function (name, script, bold, italic) {
4173 if ($libmupdf_load_font_file_js) {
4174 var font = $libmupdf_load_font_file_js(fromString(name), fromString(script), bold, italic)
4175 if (font) {
4176 checkType(font, Font)
4177 return font.pointer
4178 }
4179 }
4180 return 0 as Pointer<"fz_font">
4181 }
4182
4183 interface DeviceFunctions {
4184 drop?(): void,
4185 close?(): void,
4186
4187 fillPath?(path: Path, evenOdd: boolean, ctm: Matrix, colorspace: ColorSpace, color: number[], alpha: number): void,
4188 strokePath?(path: Path, stroke: StrokeState, ctm: Matrix, colorspace: ColorSpace, color: number[], alpha: number): void,
4189 clipPath?(path: Path, evenOdd: boolean, ctm: Matrix): void,
4190 clipStrokePath?(path: Path, stroke: StrokeState, ctm: Matrix): void,
4191
4192 fillText?(text: Text, ctm: Matrix, colorspace: ColorSpace, color: number[], alpha: number): void,
4193 strokeText?(text: Text, stroke: StrokeState, ctm: Matrix, colorspace: ColorSpace, color: number[], alpha: number): void,
4194 clipText?(text: Text, ctm: Matrix): void,
4195 clipStrokeText?(text: Text, stroke: StrokeState, ctm: Matrix): void,
4196 ignoreText?(text: Text, ctm: Matrix): void,
4197
4198 fillShade?(shade: Shade, ctm: Matrix, alpha: number): void,
4199
4200 fillImage?(image: Image, ctm: Matrix, alpha: number): void,
4201 fillImageMask?(image: Image, ctm: Matrix, colorspace: ColorSpace, color: number[], alpha: number): void,
4202 clipImageMask?(image: Image, ctm: Matrix): void,
4203
4204 popClip?(): void,
4205
4206 beginMask?(bbox: Rect, luminosity: boolean, colorspace: ColorSpace, color: number[]): void,
4207 endMask?(): void,
4208
4209 beginGroup?(bbox: Rect, colorspace: ColorSpace, isolated: boolean, knockout: boolean, blendmode: BlendMode, alpha: number): void,
4210 endGroup?(): void,
4211
4212 beginTile?(area: Rect, view: Rect, xstep: number, ystep: number, ctm: Matrix, id: number, doc_id: number): number,
4213 endTile?(): void,
4214
4215 beginLayer?(name: string): void,
4216 endLayer?(): void,
4217 }
4218
4219 var $libmupdf_device_id = 0
4220 var $libmupdf_device_table: Map<number,DeviceFunctions> = new Map()
4221
4222 var $libmupdf_path_id = 0
4223 var $libmupdf_path_table: Map<number,PathWalker> = new Map()
4224
4225 var $libmupdf_text_id = 0
4226 var $libmupdf_text_table: Map<number,TextWalker> = new Map()
4227
4228 declare global {
4229 var $libmupdf_path_walk: any
4230 var $libmupdf_text_walk: any
4231 var $libmupdf_device: any
4232 }
4233
4234 globalThis.$libmupdf_path_walk = {
4235 moveto(id: number, x: number, y: number): void {
4236 $libmupdf_path_table.get(id)?.moveTo?.(x, y)
4237 },
4238 lineto(id: number, x: number, y: number): void {
4239 $libmupdf_path_table.get(id)?.lineTo?.(x, y)
4240 },
4241 curveto(id: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): void {
4242 $libmupdf_path_table.get(id)?.curveTo?.(x1, y1, x2, y2, x3, y3)
4243 },
4244 closepath(id: number): void {
4245 $libmupdf_path_table.get(id)?.closePath?.()
4246 },
4247 }
4248
4249 var $libmupdf_text_font: Font | null = null
4250
4251 globalThis.$libmupdf_text_walk = {
4252 begin_span(
4253 id: number,
4254 font: Pointer<"fz_font">,
4255 trm: Pointer<"fz_matrix">,
4256 wmode: number,
4257 bidi: number,
4258 dir: number,
4259 lang: Pointer<"char">
4260 ): void {
4261 if (font !== $libmupdf_text_font?.pointer)
4262 $libmupdf_text_font = new Font(font)
4263 $libmupdf_text_table.get(id)?.beginSpan?.(
4264 $libmupdf_text_font,
4265 fromMatrix(trm),
4266 wmode,
4267 bidi,
4268 dir,
4269 fromString(lang)
4270 )
4271 },
4272 end_span(id: number): void {
4273 $libmupdf_text_table.get(id)?.endSpan?.()
4274 },
4275 show_glyph(
4276 id: number,
4277 font: Pointer<"fz_font">,
4278 trm: Pointer<"fz_matrix">,
4279 glyph: number,
4280 unicode: number,
4281 wmode: number,
4282 bidi: number
4283 ): void {
4284 if (font !== $libmupdf_text_font?.pointer)
4285 $libmupdf_text_font = new Font(font)
4286 $libmupdf_text_table.get(id)?.showGlyph?.(
4287 $libmupdf_text_font,
4288 fromMatrix(trm),
4289 glyph,
4290 unicode,
4291 wmode,
4292 bidi
4293 )
4294 },
4295 }
4296
4297 globalThis.$libmupdf_device = {
4298 drop_device(id: number): void {
4299 $libmupdf_device_table.get(id)?.drop?.()
4300 $libmupdf_device_table.delete(id)
4301 },
4302
4303 close_device(id: number): void {
4304 $libmupdf_device_table.get(id)?.close?.()
4305 },
4306
4307 fill_path(
4308 id: number,
4309 path: Pointer<"fz_path">,
4310 even_odd: number,
4311 ctm: Pointer<"fz_matrix">,
4312 colorspace: Pointer<"fz_colorspace">,
4313 color_n: number,
4314 color_arr: Pointer<"float">,
4315 alpha: number
4316 ): void {
4317 $libmupdf_device_table.get(id)?.fillPath?.(
4318 new Path(libmupdf._wasm_keep_path(path)),
4319 !!even_odd,
4320 fromMatrix(ctm),
4321 new ColorSpace(libmupdf._wasm_keep_colorspace(colorspace)),
4322 fromColorArray(color_n, color_arr),
4323 alpha
4324 )
4325 },
4326
4327 clip_path(
4328 id: number,
4329 path: Pointer<"fz_path">,
4330 even_odd: number,
4331 ctm: Pointer<"fz_matrix">
4332 ): void {
4333 $libmupdf_device_table.get(id)?.clipPath?.(
4334 new Path(libmupdf._wasm_keep_path(path)),
4335 !!even_odd,
4336 fromMatrix(ctm)
4337 )
4338 },
4339
4340 stroke_path(
4341 id: number,
4342 path: Pointer<"fz_path">,
4343 stroke: Pointer<"fz_stroke_state">,
4344 ctm: Pointer<"fz_matrix">,
4345 colorspace: Pointer<"fz_colorspace">,
4346 color_n: number,
4347 color_arr: Pointer<"float">,
4348 alpha: number
4349 ): void {
4350 $libmupdf_device_table.get(id)?.strokePath?.(
4351 new Path(libmupdf._wasm_keep_path(path)),
4352 new StrokeState(libmupdf._wasm_keep_stroke_state(stroke)),
4353 fromMatrix(ctm),
4354 new ColorSpace(libmupdf._wasm_keep_colorspace(colorspace)),
4355 fromColorArray(color_n, color_arr),
4356 alpha
4357 )
4358 },
4359
4360 clip_stroke_path(
4361 id: number,
4362 path: Pointer<"fz_path">,
4363 stroke: Pointer<"fz_stroke_state">,
4364 ctm: Pointer<"fz_matrix">
4365 ): void {
4366 $libmupdf_device_table.get(id)?.clipStrokePath?.(
4367 new Path(libmupdf._wasm_keep_path(path)),
4368 new StrokeState(libmupdf._wasm_keep_stroke_state(stroke)),
4369 fromMatrix(ctm)
4370 )
4371 },
4372
4373 fill_text(
4374 id: number,
4375 text: Pointer<"fz_text">,
4376 ctm: Pointer<"fz_matrix">,
4377 colorspace: Pointer<"fz_colorspace">,
4378 color_n: number,
4379 color_arr: Pointer<"float">,
4380 alpha: number
4381 ): void {
4382 $libmupdf_device_table.get(id)?.fillText?.(
4383 new Text(libmupdf._wasm_keep_text(text)),
4384 fromMatrix(ctm),
4385 new ColorSpace(libmupdf._wasm_keep_colorspace(colorspace)),
4386 fromColorArray(color_n, color_arr),
4387 alpha
4388 )
4389 },
4390
4391 stroke_text(
4392 id: number,
4393 text: Pointer<"fz_text">,
4394 stroke: Pointer<"fz_stroke_state">,
4395 ctm: Pointer<"fz_matrix">,
4396 colorspace: Pointer<"fz_colorspace">,
4397 color_n: number,
4398 color_arr: Pointer<"float">,
4399 alpha: number
4400 ): void {
4401 $libmupdf_device_table.get(id)?.strokeText?.(
4402 new Text(libmupdf._wasm_keep_text(text)),
4403 new StrokeState(libmupdf._wasm_keep_stroke_state(stroke)),
4404 fromMatrix(ctm),
4405 new ColorSpace(libmupdf._wasm_keep_colorspace(colorspace)),
4406 fromColorArray(color_n, color_arr),
4407 alpha
4408 )
4409 },
4410
4411 clip_text(
4412 id: number,
4413 text: Pointer<"fz_text">,
4414 ctm: Pointer<"fz_matrix">
4415 ): void {
4416 $libmupdf_device_table.get(id)?.clipText?.(
4417 new Text(libmupdf._wasm_keep_text(text)),
4418 fromMatrix(ctm)
4419 )
4420 },
4421
4422 clip_stroke_text(
4423 id: number,
4424 text: Pointer<"fz_text">,
4425 stroke: Pointer<"fz_stroke_state">,
4426 ctm: Pointer<"fz_matrix">,
4427 ): void {
4428 $libmupdf_device_table.get(id)?.clipStrokeText?.(
4429 new Text(libmupdf._wasm_keep_text(text)),
4430 new StrokeState(libmupdf._wasm_keep_stroke_state(stroke)),
4431 fromMatrix(ctm)
4432 )
4433 },
4434
4435 ignore_text(
4436 id: number,
4437 text: Pointer<"fz_text">,
4438 ctm: Pointer<"fz_matrix">
4439 ): void {
4440 $libmupdf_device_table.get(id)?.ignoreText?.(
4441 new Text(libmupdf._wasm_keep_text(text)),
4442 fromMatrix(ctm)
4443 )
4444 },
4445
4446 fill_shade(
4447 id: number,
4448 shade: Pointer<"fz_shade">,
4449 ctm: Pointer<"fz_matrix">,
4450 alpha: number
4451 ): void {
4452 $libmupdf_device_table.get(id)?.fillShade?.(
4453 new Shade(shade),
4454 fromMatrix(ctm),
4455 alpha
4456 )
4457 },
4458
4459 fill_image(
4460 id: number,
4461 image: Pointer<"fz_image">,
4462 ctm: Pointer<"fz_matrix">,
4463 alpha: number
4464 ): void {
4465 $libmupdf_device_table.get(id)?.fillImage?.(
4466 new Image(image),
4467 fromMatrix(ctm),
4468 alpha
4469 )
4470 },
4471
4472 fill_image_mask(
4473 id: number,
4474 image: Pointer<"fz_image">,
4475 ctm: Pointer<"fz_matrix">,
4476 colorspace: Pointer<"fz_colorspace">,
4477 color_n: number,
4478 color_arr: Pointer<"float">,
4479 alpha: number
4480 ): void {
4481 $libmupdf_device_table.get(id)?.fillImageMask?.(
4482 new Image(image),
4483 fromMatrix(ctm),
4484 new ColorSpace(libmupdf._wasm_keep_colorspace(colorspace)),
4485 fromColorArray(color_n, color_arr),
4486 alpha
4487 )
4488 },
4489
4490 clip_image_mask(
4491 id: number,
4492 image: Pointer<"fz_image">,
4493 ctm: Pointer<"fz_matrix">
4494 ): void {
4495 $libmupdf_device_table.get(id)?.clipImageMask?.(
4496 new Image(image),
4497 fromMatrix(ctm)
4498 )
4499 },
4500
4501 pop_clip(id: number): void {
4502 $libmupdf_device_table.get(id)?.popClip?.()
4503 },
4504
4505 begin_mask(
4506 id: number,
4507 bbox: Pointer<"fz_rect">,
4508 luminosity: number,
4509 colorspace: Pointer<"fz_colorspace">,
4510 color_n: number,
4511 color_arr: Pointer<"float">
4512 ): void {
4513 $libmupdf_device_table.get(id)?.beginMask?.(
4514 fromRect(bbox),
4515 !!luminosity,
4516 new ColorSpace(libmupdf._wasm_keep_colorspace(colorspace)),
4517 fromColorArray(color_n, color_arr)
4518 )
4519 },
4520
4521 begin_group(
4522 id: number,
4523 bbox: Pointer<"fz_rect">,
4524 colorspace: Pointer<"fz_colorspace">,
4525 isolated: number,
4526 knockout: number,
4527 blendmode: number,
4528 alpha: number
4529 ): void {
4530 $libmupdf_device_table.get(id)?.beginGroup?.(
4531 fromRect(bbox),
4532 new ColorSpace(libmupdf._wasm_keep_colorspace(colorspace)),
4533 !!isolated,
4534 !!knockout,
4535 Device.BLEND_MODES[blendmode] as BlendMode,
4536 alpha
4537 )
4538 },
4539
4540 begin_tile(
4541 id: number,
4542 area: Pointer<"fz_rect">,
4543 view: Pointer<"fz_rect">,
4544 xstep: number,
4545 ystep: number,
4546 ctm: Pointer<"fz_matrix">,
4547 tile_id: number,
4548 doc_id: number
4549 ): number {
4550 return $libmupdf_device_table.get(id)?.beginTile?.(
4551 fromRect(area),
4552 fromRect(view),
4553 xstep,
4554 ystep,
4555 fromMatrix(ctm),
4556 tile_id,
4557 doc_id
4558 ) || 0
4559 },
4560
4561 begin_layer(id: number, name: Pointer<"char">): void {
4562 $libmupdf_device_table.get(id)?.beginLayer?.(
4563 fromString(name)
4564 )
4565 },
4566
4567 end_mask(id: number): void {
4568 $libmupdf_device_table.get(id)?.endMask?.()
4569 },
4570
4571 end_group(id: number): void {
4572 $libmupdf_device_table.get(id)?.endGroup?.()
4573 },
4574
4575 end_tile(id: number): void {
4576 $libmupdf_device_table.get(id)?.endTile?.()
4577 },
4578
4579 end_layer(id: number): void {
4580 $libmupdf_device_table.get(id)?.endLayer?.()
4581 },
4582
4583 }
4584
4585 /* default exports */
4586 export default {
4587 // const
4588 Matrix,
4589 Rect,
4590
4591 // function
4592 enableICC,
4593 disableICC,
4594 setUserCSS,
4595 installLoadFontFunction,
4596
4597 // class
4598 Buffer,
4599 ColorSpace,
4600 Font,
4601 Image,
4602 StrokeState,
4603 Path,
4604 Text,
4605 DisplayList,
4606 Pixmap,
4607 Shade,
4608 StructuredText,
4609 Device,
4610 DrawDevice,
4611 DisplayListDevice,
4612 DocumentWriter,
4613 Document,
4614 OutlineIterator,
4615 Link,
4616 Page,
4617 PDFDocument,
4618 PDFPage,
4619 PDFObject,
4620 PDFGraftMap,
4621 PDFAnnotation,
4622 PDFWidget,
4623 Stream,
4624
4625 // debugging
4626 memento
4627 }