@aboutgeo/pdiiif 0.0.0-stage → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +169 -2
  2. package/dist/__tests__/parser.test.d.ts +1 -0
  3. package/dist/__tests__/pdf.spec.d.ts +1 -0
  4. package/dist/__tests__/region.test.d.ts +1 -0
  5. package/dist/__tests__/setupJest.d.ts +0 -0
  6. package/dist/assets/optimization.worker-C8u4PFfM.js +886 -0
  7. package/dist/assets/optimization.worker-C8u4PFfM.js.map +1 -0
  8. package/dist/convert.d.ts +223 -0
  9. package/dist/download.d.ts +115 -0
  10. package/dist/iiif.d.ts +110 -0
  11. package/dist/index.cjs +65 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.mjs +11137 -0
  15. package/dist/index.mjs.map +1 -0
  16. package/dist/io.d.ts +75 -0
  17. package/dist/log.d.ts +21 -0
  18. package/dist/metrics.d.ts +10 -0
  19. package/dist/ocr.d.ts +36 -0
  20. package/dist/optimization.d.ts +48 -0
  21. package/dist/optimization.worker.d.ts +1 -0
  22. package/dist/pdf/annos-text.d.ts +19 -0
  23. package/dist/pdf/annos.d.ts +4 -0
  24. package/dist/pdf/common.d.ts +48 -0
  25. package/dist/pdf/generator.d.ts +197 -0
  26. package/dist/pdf/image.d.ts +34 -0
  27. package/dist/pdf/parser.d.ts +131 -0
  28. package/dist/pdf/pkzip.d.ts +23 -0
  29. package/dist/pdf/png.d.ts +34 -0
  30. package/dist/pdf/util.d.ts +18 -0
  31. package/dist/res/licenses.d.ts +7 -0
  32. package/dist/res/srgbColorspace.d.ts +2 -0
  33. package/dist/util.d.ts +8 -0
  34. package/dist/version.d.ts +2 -0
  35. package/package.json +149 -4
  36. package/src/__tests__/fixtures/deep_toc.json +2953 -0
  37. package/src/__tests__/fixtures/flat_toc.json +2917 -0
  38. package/src/__tests__/fixtures/physdim.json +294 -0
  39. package/src/__tests__/fixtures/region_target.json +58 -0
  40. package/src/__tests__/fixtures/wunder.jpg +0 -0
  41. package/src/__tests__/parser.test.ts +42 -0
  42. package/src/__tests__/pdf.spec.ts +216 -0
  43. package/src/__tests__/region.test.ts +194 -0
  44. package/src/__tests__/setupJest.ts +2 -0
  45. package/src/convert.ts +1098 -0
  46. package/src/download.ts +703 -0
  47. package/src/global.d.ts +10 -0
  48. package/src/iiif.ts +605 -0
  49. package/src/index.ts +7 -0
  50. package/src/io.ts +243 -0
  51. package/src/log.ts +51 -0
  52. package/src/metrics.ts +47 -0
  53. package/src/ocr.ts +176 -0
  54. package/src/optimization.ts +201 -0
  55. package/src/optimization.worker.ts +118 -0
  56. package/src/pdf/annos-text.ts +382 -0
  57. package/src/pdf/annos.ts +240 -0
  58. package/src/pdf/common.ts +158 -0
  59. package/src/pdf/generator.ts +1665 -0
  60. package/src/pdf/image.ts +340 -0
  61. package/src/pdf/parser.ts +811 -0
  62. package/src/pdf/pkzip.ts +228 -0
  63. package/src/pdf/png.ts +397 -0
  64. package/src/pdf/util.ts +111 -0
  65. package/src/res/licenses.ts +266 -0
  66. package/src/res/srgbColorspace.ts +405 -0
  67. package/src/types.d.ts +6 -0
  68. package/src/util.ts +55 -0
  69. package/src/version.ts +1 -0
@@ -0,0 +1,240 @@
1
+ import { PdfDictionary } from './common.js';
2
+ import { Annotation } from '../iiif.js';
3
+ import {
4
+ BoxSelector,
5
+ SelectorStyle,
6
+ SupportedSelector,
7
+ SvgSelector,
8
+ } from '@iiif/helpers';
9
+ import { PointSelector } from '@iiif/presentation-3';
10
+ import Color from 'color';
11
+ import { SAXParser, SaxEventType, Text } from 'sax-wasm';
12
+ import { saxParserWasm } from '../util.js';
13
+ import { textEncoder } from './util.js';
14
+
15
+ const CSS_LENGTH_PAT = /(?<val>\d+(?:\.\d+)?)\s*(?<unit>[[a-z%]+)?/;
16
+
17
+ async function htmlToPlainText(html: string): Promise<string> {
18
+ if (!saxParserWasm) {
19
+ throw new Error('SAX parser WebAssembly has not been initialized');
20
+ }
21
+ const parser = new SAXParser(SaxEventType.Text);
22
+ await parser.prepareWasm(saxParserWasm);
23
+ const txt: string[] = [];
24
+ parser.eventHandler = (ev, data) => {
25
+ txt.push((data as Text).value);
26
+ }
27
+ parser.write(textEncoder.encode(html));
28
+ parser.end();
29
+ return txt.join('').trim();
30
+ }
31
+
32
+ function toPdfRect(
33
+ selector: BoxSelector | SvgSelector,
34
+ pageHeight: number,
35
+ unitScale: number
36
+ ): PdfDictionary | null {
37
+ if (!selector.spatial) {
38
+ return null;
39
+ }
40
+ const lowerY = pageHeight - selector.spatial.y - selector.spatial.height;
41
+ const upperY = pageHeight - selector.spatial.y;
42
+ return {
43
+ Subtype: '/Square',
44
+ Rect: [
45
+ selector.spatial.x * unitScale,
46
+ lowerY * unitScale,
47
+ (selector.spatial.x + selector.spatial.width) * unitScale,
48
+ upperY * unitScale,
49
+ ],
50
+ };
51
+ }
52
+
53
+ function cssColorToRgb(cssColor: string): [number, number, number] | null {
54
+ return Color(cssColor).rgb().array() as [number, number, number];
55
+ }
56
+
57
+ function cssLengthToPdfUserspace(
58
+ cssLength: string,
59
+ unitScale: number,
60
+ referenceDimensionPx?: number
61
+ ): number | null {
62
+ const match = CSS_LENGTH_PAT.exec(cssLength);
63
+ if (!match || !match.groups) {
64
+ return null;
65
+ }
66
+ const val = parseFloat(match.groups.val);
67
+ const unit = match.groups.unit;
68
+ if (!unit) {
69
+ return val * unitScale;
70
+ }
71
+ switch (unit) {
72
+ case '%':
73
+ if (!referenceDimensionPx) {
74
+ return null;
75
+ }
76
+ return (val / 100) * referenceDimensionPx * unitScale;
77
+ case 'px':
78
+ return unitScale * val;
79
+ default:
80
+ console.warn(`Unsupported CSS length unit: ${unit}`);
81
+ return null;
82
+ }
83
+ }
84
+
85
+ function selectorStyleToPdf(
86
+ style: SelectorStyle,
87
+ unitScale: number
88
+ ): PdfDictionary {
89
+ const pdfStyle: PdfDictionary = {};
90
+ if (style.stroke || style.strokeDasharray || style.strokeWidth) {
91
+ pdfStyle.BS = {
92
+ Type: '/Border',
93
+ W: style.strokeWidth ?? 1,
94
+ S: style.strokeDasharray ? '/D' : '/S',
95
+ };
96
+ if (style.strokeDasharray) {
97
+ pdfStyle.BS.D = style.strokeDasharray;
98
+ }
99
+ }
100
+ if (style.fill) {
101
+ const rgb = cssColorToRgb(style.fill);
102
+ if (rgb) {
103
+ pdfStyle.IC = rgb.map((c) => c / 255);
104
+ }
105
+ }
106
+ // TODO: Check if fill-opacity is desired and use an Apperance Stream instead of IC
107
+ if (style.strokeWidth) {
108
+ const width = cssLengthToPdfUserspace(style.strokeWidth, unitScale);
109
+ pdfStyle.BS = {
110
+ Type: '/Border',
111
+ W: width,
112
+ };
113
+ }
114
+ return pdfStyle;
115
+ }
116
+
117
+ function selectorToPdf(
118
+ selector: SupportedSelector,
119
+ unitScale: number,
120
+ pageHeight: number
121
+ ): PdfDictionary {
122
+ const styleDict = selector.style
123
+ ? selectorStyleToPdf(selector.style, unitScale)
124
+ : {};
125
+ switch (selector.type) {
126
+ case 'BoxSelector':
127
+ return {
128
+ Subtype: '/Square',
129
+ ...toPdfRect(selector as BoxSelector, pageHeight, unitScale),
130
+ ...styleDict,
131
+ };
132
+ case 'PointSelector': {
133
+ // TODO: Use a /Stamp with a custom icon (flag?)
134
+ // This is a bit complicated since we need to povide
135
+ // an /AP dictionary with a custom /Form that
136
+ // renders our icon. Luckily, this can be reused, so
137
+ // we store it once and just reference it in all point-type
138
+ // annotations.
139
+ const point = selector as PointSelector;
140
+ if (!point.x || !point.y) {
141
+ throw `Only PointSelectors with both x and y coordinates are supported!`;
142
+ }
143
+ return {
144
+ Subtype: '/Circle',
145
+ BS: {
146
+ Type: '/Border',
147
+ W: 2,
148
+ S: '/S',
149
+ },
150
+ IC: [1.0, 1.0, 1.0],
151
+ Rect: [
152
+ point.x * unitScale - 0.5,
153
+ point.y * unitScale - 0.5,
154
+ point.x * unitScale + 1.0,
155
+ point.y * unitScale + 1.0,
156
+ ],
157
+ };
158
+ }
159
+ case 'SvgSelector': {
160
+ const svgSel = selector as SvgSelector;
161
+ switch (svgSel.svgShape) {
162
+ case 'rect':
163
+ return {
164
+ Subtype: '/Square',
165
+ ...toPdfRect(svgSel, pageHeight, unitScale),
166
+ ...styleDict,
167
+ };
168
+ case 'circle':
169
+ case 'ellipse':
170
+ return {
171
+ Subtype: '/Circle',
172
+ Rect: toPdfRect(svgSel, pageHeight, unitScale),
173
+ ...styleDict,
174
+ };
175
+ case 'polyline':
176
+ case 'polygon':
177
+ return {
178
+ Subtype: svgSel.svgShape === 'polyline' ? '/PolyLine' : '/Polygon',
179
+ Vertices:
180
+ svgSel.points?.flatMap(([x, y]) => [
181
+ x * unitScale,
182
+ (pageHeight - y) * unitScale,
183
+ ]) ?? [],
184
+ ...styleDict,
185
+ };
186
+ case 'path':
187
+ return {
188
+ Subtype: '/Ink',
189
+ InkList:
190
+ svgSel.points?.flatMap(([x, y]) => [
191
+ x * unitScale,
192
+ (pageHeight - y) * unitScale,
193
+ ]) ?? [],
194
+ ...styleDict,
195
+ };
196
+ default:
197
+ throw new Error('not implemented yet');
198
+ }
199
+ }
200
+ default:
201
+ throw `${selector.type} selector is currently not supported`;
202
+ }
203
+ }
204
+
205
+ export async function exportPdfAnnotation(
206
+ anno: Annotation,
207
+ unitScale: number,
208
+ pageHeight: number
209
+ ): Promise<Array<PdfDictionary>> {
210
+ const annoDict: PdfDictionary = {
211
+ Type: '/Annot',
212
+ NM: `(${anno.id})`,
213
+ Contents: `(${await htmlToPlainText(anno.markup)})`,
214
+ F: 4,
215
+ C: [1, 0, 0], // Red title bar
216
+ CA: 1, // Constant opacity of 1
217
+ Border: [0, 0, 5],
218
+ //RC: `(${htmlToPdfRichText(anno.markup)})`,
219
+ };
220
+ if (anno.author) {
221
+ annoDict.T = `(${anno.author})`;
222
+ }
223
+ if (anno.lastModified) {
224
+ annoDict.M = anno.lastModified;
225
+ }
226
+ if (anno.target.selector) {
227
+ return [
228
+ {
229
+ ...annoDict,
230
+ ...selectorToPdf(anno.target.selector, unitScale, pageHeight),
231
+ },
232
+ ] as PdfDictionary[];
233
+ } else if (anno.target.selectors && anno.target.selectors.length > 0) {
234
+ return anno.target.selectors.map((s) => ({
235
+ ...annoDict,
236
+ ...selectorToPdf(s, unitScale, pageHeight),
237
+ })) as PdfDictionary[];
238
+ }
239
+ return [];
240
+ }
@@ -0,0 +1,158 @@
1
+ import { IS_BIG_ENDIAN } from './util.js';
2
+
3
+ const PDF_INDENTATION = 2;
4
+
5
+ export interface Metadata {
6
+ Producer?: string;
7
+ Creator?: string;
8
+ CreationDate?: Date;
9
+ Title?: string;
10
+ Author?: string;
11
+ Keywords?: string;
12
+ ModDate?: Date;
13
+ }
14
+
15
+ export interface PdfObject {
16
+ num: number;
17
+ data?: PdfValue;
18
+ stream?: Uint8Array | string;
19
+ }
20
+
21
+ export class PdfRef {
22
+ refObj: number;
23
+
24
+ constructor(num: number) {
25
+ this.refObj = num;
26
+ }
27
+ }
28
+ export type PdfPrimitive =
29
+ | string
30
+ | number
31
+ | boolean
32
+ | Uint8Array
33
+ | null
34
+ | Date
35
+ | PdfRef;
36
+ export interface PdfDictionary {
37
+ [member: string]: PdfPrimitive | PdfArray | PdfDictionary;
38
+ }
39
+ export type PdfArray = Array<PdfPrimitive | PdfArray | PdfDictionary>;
40
+ export type PdfValue = PdfPrimitive | PdfDictionary | PdfArray | null;
41
+
42
+ export interface PdfAnnotation {
43
+ Type: 'Annot';
44
+ Subtype: string;
45
+ Rect: [number, number, number, number];
46
+ Contents: string | undefined;
47
+ P?: PdfRef;
48
+ NM?: string;
49
+ M?: Date;
50
+ F?: number;
51
+ AP?: PdfDictionary;
52
+ AS?: string;
53
+ Border?: [number, number, number] | [number, number, number, number];
54
+ C?:
55
+ | []
56
+ | [number]
57
+ | [number, number, number]
58
+ | [number, number, number, number];
59
+ }
60
+
61
+ export interface StructTreeEntry {
62
+ type: 'Sect' | 'P' | 'Span';
63
+ children: Array<StructTreeEntry>; // Only for `Sect` and `P` entries
64
+ pageObjNum: number;
65
+ mcs: Array<number>; // Only for `Span` entries
66
+ }
67
+
68
+ export function makeRef(target: number | PdfObject): PdfRef {
69
+ const num = typeof target === 'number' ? target : target.num;
70
+ return new PdfRef(num);
71
+ }
72
+
73
+ function isUnicode(str: string): boolean {
74
+ for (let i = 0, end = str.length; i < end; i++) {
75
+ if (str.charCodeAt(i) > 0x7f) {
76
+ return true;
77
+ }
78
+ }
79
+ return false;
80
+ }
81
+
82
+ /** Convert a JS UTF8 string to a UTF16 Big Endian string */
83
+ export function toUTF16BE(str: string, includeBom = true): Uint8Array {
84
+ const buf = new Uint16Array(str.length + (includeBom ? 1 : 0));
85
+ for (let i = includeBom ? 1 : 0; i < buf.length; i++) {
86
+ buf[i] = str.charCodeAt(i - (includeBom ? 1 : 0));
87
+ }
88
+ const outBuf = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
89
+ if (!IS_BIG_ENDIAN) {
90
+ // PDF needs UTF16-BE, so in little endian systems we need to swap each
91
+ // codepoint's byte pair
92
+ for (let i = includeBom ? 2 : 0, end = outBuf.length - 1; i < end; i += 2) {
93
+ const a = outBuf[i];
94
+ outBuf[i] = outBuf[i + 1];
95
+ outBuf[i + 1] = a;
96
+ }
97
+ }
98
+ // UTF16BE BOM
99
+ if (includeBom) {
100
+ outBuf[0] = 254;
101
+ outBuf[1] = 255;
102
+ }
103
+ return outBuf;
104
+ }
105
+
106
+ function safeNumber(num: number): number {
107
+ if (num > -1e21 && num < 1e21) {
108
+ return Math.round(num * 1e6) / 1e6;
109
+ }
110
+ throw new Error(`unsupported number: ${num}`);
111
+ }
112
+
113
+ export function serialize(value: PdfValue, dictIndent = 0): string {
114
+ if (typeof value === 'string') {
115
+ if (
116
+ value[0] === '(' &&
117
+ value[value.length - 1] === ')' &&
118
+ isUnicode(value)
119
+ ) {
120
+ return serialize(toUTF16BE(value.substring(1, value.length - 1)));
121
+ }
122
+ return value;
123
+ } else if (value instanceof Uint8Array) {
124
+ return `<${Array.from(value)
125
+ .map((x) => x.toString(16).padStart(2, '0').toUpperCase())
126
+ .join('')}>`;
127
+ } else if (value instanceof Date) {
128
+ const dateString =
129
+ `D:${value.getUTCFullYear().toString(10).padStart(4, '0')}` +
130
+ (value.getUTCMonth() + 1).toString(10).padStart(2, '0') +
131
+ value.getUTCDate().toString(10).padStart(2, '0') +
132
+ value.getUTCHours().toString(10).padStart(2, '0') +
133
+ value.getUTCMinutes().toString(10).padStart(2, '0') +
134
+ value.getUTCSeconds().toString(10).padStart(2, '0') +
135
+ 'Z';
136
+ return `(${dateString})`;
137
+ } else if (Array.isArray(value)) {
138
+ return `[${value.map((v) => serialize(v, dictIndent + 1)).join(' ')}]`;
139
+ } else if (value instanceof PdfRef) {
140
+ if (value.refObj === -1) {
141
+ throw new Error('Cannot serialize a deferred object reference');
142
+ }
143
+ return `${value.refObj} 0 R`;
144
+ } else if ({}.toString.call(value) === '[object Object]') {
145
+ const outsideIndent = ' '.repeat(PDF_INDENTATION * dictIndent);
146
+ const insideIndent = outsideIndent + ' '.repeat(PDF_INDENTATION);
147
+ return `<<\n${Object.entries(value as any)
148
+ .map(
149
+ ([k, v]) =>
150
+ `${insideIndent}/${k} ${serialize(v as any, dictIndent + 1)}`
151
+ )
152
+ .join('\n')}\n${outsideIndent}>>`;
153
+ } else if (typeof value === 'number') {
154
+ return safeNumber(value).toString(10);
155
+ } else {
156
+ return `${value}`;
157
+ }
158
+ }