0
# Configuration API
1
2
Global configuration options and web worker management for optimal performance and browser compatibility. Controls PDF.js runtime behavior and resource loading.
3
4
## Capabilities
5
6
### Global Worker Options
7
8
Configuration for PDF.js web worker, which handles PDF parsing and processing in a separate thread for better performance.
9
10
```javascript { .api }
11
const GlobalWorkerOptions: {
12
/** Path to PDF.js worker script */
13
workerSrc: string;
14
/** Custom worker port for advanced scenarios */
15
workerPort?: MessagePort;
16
};
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
import { GlobalWorkerOptions } from "pdfjs-dist";
23
24
// Set worker source (required before loading documents)
25
GlobalWorkerOptions.workerSrc = "/node_modules/pdfjs-dist/build/pdf.worker.mjs";
26
27
// For webpack or bundler environments
28
GlobalWorkerOptions.workerSrc = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/5.4.149/pdf.worker.mjs";
29
30
// For local development
31
GlobalWorkerOptions.workerSrc = "./pdf.worker.mjs";
32
```
33
34
### PDF Worker
35
36
Custom worker management for advanced use cases and multi-document scenarios.
37
38
```javascript { .api }
39
class PDFWorker {
40
/** Worker name identifier */
41
name: string;
42
/** Whether worker is destroyed */
43
destroyed: boolean;
44
/** Worker message port */
45
port: MessagePort;
46
/** Worker message handler */
47
messageHandler: MessageHandler;
48
49
/**
50
* Constructor for custom PDF worker
51
* @param params - Worker parameters
52
*/
53
constructor(params?: PDFWorkerParameters);
54
55
/**
56
* Destroy the worker and clean up resources
57
*/
58
destroy(): void;
59
60
/**
61
* Create worker from existing port
62
* @param params - Port parameters
63
* @returns PDF worker instance
64
*/
65
static fromPort(params: FromPortParameters): PDFWorker;
66
67
/**
68
* Get the configured worker source URL
69
* @returns Worker source URL
70
*/
71
static getWorkerSrc(): string;
72
}
73
74
interface PDFWorkerParameters {
75
/** Worker name */
76
name?: string;
77
/** Custom worker port */
78
port?: MessagePort;
79
/** Verbosity level */
80
verbosity?: number;
81
}
82
83
interface FromPortParameters {
84
/** Worker name */
85
name?: string;
86
/** Message port */
87
port: MessagePort;
88
/** Verbosity level */
89
verbosity?: number;
90
}
91
```
92
93
**Usage Examples:**
94
95
```javascript
96
import { PDFWorker } from "pdfjs-dist";
97
98
// Create custom worker for multiple documents
99
const worker = new PDFWorker({ name: "myWorker" });
100
101
// Use worker in document loading
102
const loadingTask = getDocument({
103
url: "document1.pdf",
104
worker: worker
105
});
106
107
const pdf1 = await loadingTask.promise;
108
109
// Reuse same worker for another document
110
const loadingTask2 = getDocument({
111
url: "document2.pdf",
112
worker: worker
113
});
114
115
const pdf2 = await loadingTask2.promise;
116
117
// Clean up when done
118
worker.destroy();
119
```
120
121
### Feature Detection
122
123
Runtime feature detection for browser capabilities and PDF.js optimizations.
124
125
```javascript { .api }
126
const FeatureTest: {
127
/** Platform information */
128
platform: {
129
isLittleEndian: boolean;
130
isEvalSupported: boolean;
131
isOffscreenCanvasSupported: boolean;
132
canvasMaxAreaInBytes: number;
133
};
134
135
/** Check for specific feature support */
136
checkFeature(feature: string): boolean;
137
};
138
```
139
140
### Verbosity Levels
141
142
Logging and debugging configuration.
143
144
```javascript { .api }
145
enum VerbosityLevel {
146
ERRORS = 0,
147
WARNINGS = 1,
148
INFOS = 5
149
}
150
151
/**
152
* Set global verbosity level for debugging
153
* @param level - Verbosity level
154
*/
155
function setVerbosityLevel(level: number): void;
156
157
/**
158
* Get current verbosity level
159
* @returns Current verbosity level
160
*/
161
function getVerbosityLevel(): number;
162
```
163
164
**Usage Examples:**
165
166
```javascript
167
import { setVerbosityLevel, VerbosityLevel } from "pdfjs-dist";
168
169
// Enable detailed logging for debugging
170
setVerbosityLevel(VerbosityLevel.INFOS);
171
172
// Show only warnings and errors
173
setVerbosityLevel(VerbosityLevel.WARNINGS);
174
175
// Show only errors (production)
176
setVerbosityLevel(VerbosityLevel.ERRORS);
177
```
178
179
### Canvas Factory Configuration
180
181
Canvas creation and management for different environments.
182
183
```javascript { .api }
184
interface CanvasFactory {
185
/**
186
* Create new canvas element
187
* @param width - Canvas width
188
* @param height - Canvas height
189
* @returns Canvas and context
190
*/
191
create(width: number, height: number): {
192
canvas: HTMLCanvasElement | OffscreenCanvas;
193
context: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
194
};
195
196
/**
197
* Reset canvas dimensions
198
* @param canvasAndContext - Canvas and context object
199
* @param width - New width
200
* @param height - New height
201
*/
202
reset(canvasAndContext: any, width: number, height: number): void;
203
204
/**
205
* Destroy canvas
206
* @param canvasAndContext - Canvas and context to destroy
207
*/
208
destroy(canvasAndContext: any): void;
209
}
210
211
class DOMCanvasFactory implements CanvasFactory {
212
constructor(options?: { ownerDocument?: Document });
213
create(width: number, height: number): any;
214
reset(canvasAndContext: any, width: number, height: number): void;
215
destroy(canvasAndContext: any): void;
216
}
217
```
218
219
### CMap Reader Factory
220
221
Character mapping configuration for complex text rendering.
222
223
```javascript { .api }
224
interface CMapReaderFactory {
225
/**
226
* Fetch character mapping data
227
* @param params - Fetch parameters
228
* @returns Promise resolving to CMap data
229
*/
230
fetch(params: {
231
name: string;
232
url: string;
233
packed: boolean;
234
}): Promise<{
235
cMapData: Uint8Array;
236
compressionType: number;
237
}>;
238
}
239
240
class DOMCMapReaderFactory implements CMapReaderFactory {
241
constructor(options?: {
242
baseUrl?: string;
243
isCompressed?: boolean;
244
});
245
fetch(params: any): Promise<any>;
246
}
247
```
248
249
### Standard Font Data Factory
250
251
Font data loading configuration for PDF standard fonts.
252
253
```javascript { .api }
254
interface StandardFontDataFactory {
255
/**
256
* Fetch standard font data
257
* @param params - Font parameters
258
* @returns Promise resolving to font data
259
*/
260
fetch(params: { filename: string }): Promise<Uint8Array>;
261
}
262
263
class DOMStandardFontDataFactory implements StandardFontDataFactory {
264
constructor(options?: { baseUrl?: string });
265
fetch(params: any): Promise<Uint8Array>;
266
}
267
```
268
269
### Environment Detection
270
271
Runtime environment detection and configuration.
272
273
```javascript { .api }
274
/**
275
* Check if running in Node.js environment
276
* @returns Whether in Node.js
277
*/
278
function isNodeJS(): boolean;
279
280
/**
281
* Check if data URL scheme is supported
282
* @param url - URL to check
283
* @returns Whether data scheme is supported
284
*/
285
function isDataScheme(url: string): boolean;
286
287
/**
288
* Create valid absolute URL
289
* @param url - URL to validate
290
* @param baseUrl - Base URL for relative URLs
291
* @returns Valid absolute URL or null
292
*/
293
function createValidAbsoluteUrl(url: string, baseUrl?: string): string | null;
294
```
295
296
### Advanced Configuration
297
298
Advanced configuration options for specialized use cases.
299
300
```javascript { .api }
301
interface AdvancedPDFConfiguration {
302
/** Disable web fonts (@font-face) */
303
disableFontFace?: boolean;
304
/** Include extra font properties */
305
fontExtraProperties?: boolean;
306
/** Enable XFA form support */
307
enableXfa?: boolean;
308
/** Disable byte range requests */
309
disableRange?: boolean;
310
/** Disable streaming */
311
disableStream?: boolean;
312
/** Disable automatic data fetching */
313
disableAutoFetch?: boolean;
314
/** Maximum canvas area in bytes */
315
canvasMaxAreaInBytes?: number;
316
/** Use system fonts when available */
317
useSystemFonts?: boolean;
318
/** Enable WebGL acceleration */
319
enableWebGL?: boolean;
320
}
321
```
322
323
**Usage Examples:**
324
325
```javascript
326
// Complete PDF.js configuration setup
327
class PDFConfiguration {
328
static setup(options = {}) {
329
// Set required worker source
330
GlobalWorkerOptions.workerSrc = options.workerSrc ||
331
"/node_modules/pdfjs-dist/build/pdf.worker.mjs";
332
333
// Configure verbosity for debugging
334
if (options.debug) {
335
setVerbosityLevel(VerbosityLevel.INFOS);
336
} else {
337
setVerbosityLevel(VerbosityLevel.ERRORS);
338
}
339
340
// Feature detection
341
console.log("PDF.js Configuration:");
342
console.log("- Little Endian:", FeatureTest.platform.isLittleEndian);
343
console.log("- Eval Supported:", FeatureTest.platform.isEvalSupported);
344
console.log("- OffscreenCanvas:", FeatureTest.platform.isOffscreenCanvasSupported);
345
console.log("- Max Canvas Area:", FeatureTest.platform.canvasMaxAreaInBytes);
346
347
return {
348
// Standard configuration
349
cMapUrl: options.cMapUrl || "/node_modules/pdfjs-dist/cmaps/",
350
cMapPacked: options.cMapPacked !== false,
351
standardFontDataUrl: options.standardFontDataUrl ||
352
"/node_modules/pdfjs-dist/standard_fonts/",
353
354
// Factory configuration
355
canvasFactory: new DOMCanvasFactory(),
356
cMapReaderFactory: new DOMCMapReaderFactory({
357
baseUrl: options.cMapUrl,
358
isCompressed: options.cMapPacked
359
}),
360
standardFontDataFactory: new DOMStandardFontDataFactory({
361
baseUrl: options.standardFontDataUrl
362
}),
363
364
// Advanced options
365
disableFontFace: options.disableFontFace || false,
366
fontExtraProperties: options.fontExtraProperties || false,
367
enableXfa: options.enableXfa || false,
368
useSystemFonts: options.useSystemFonts || false,
369
enableWebGL: options.enableWebGL || false
370
};
371
}
372
373
static createWorker(name = "pdf-worker") {
374
return new PDFWorker({ name });
375
}
376
377
static async loadDocument(src, options = {}) {
378
const config = this.setup(options);
379
380
const loadingTask = getDocument({
381
...config,
382
...((typeof src === 'string') ? { url: src } : { data: src }),
383
...options
384
});
385
386
return await loadingTask.promise;
387
}
388
}
389
390
// Usage
391
const config = {
392
workerSrc: "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/5.4.149/pdf.worker.mjs",
393
cMapUrl: "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/5.4.149/cmaps/",
394
standardFontDataUrl: "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/5.4.149/standard_fonts/",
395
debug: process.env.NODE_ENV === 'development',
396
enableXfa: true,
397
useSystemFonts: true
398
};
399
400
// Load document with configuration
401
const pdf = await PDFConfiguration.loadDocument("document.pdf", config);
402
```
403
404
### Environment-Specific Configuration
405
406
```javascript { .api }
407
// Browser configuration
408
if (typeof window !== 'undefined') {
409
GlobalWorkerOptions.workerSrc = '/pdf.worker.mjs';
410
}
411
412
// Node.js configuration
413
if (typeof process !== 'undefined' && process.versions?.node) {
414
// Node.js-specific setup
415
GlobalWorkerOptions.workerSrc = require.resolve('pdfjs-dist/build/pdf.worker.js');
416
}
417
418
// Webpack configuration
419
if (typeof __webpack_require__ !== 'undefined') {
420
GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry');
421
}
422
```
423
424
### Performance Optimization
425
426
```javascript { .api }
427
/**
428
* Performance optimization settings
429
*/
430
interface PerformanceConfig {
431
/** Enable OffscreenCanvas for background rendering */
432
useOffscreenCanvas: boolean;
433
/** Maximum number of pages to cache */
434
maxPageCache: number;
435
/** Enable worker fetch for better streaming */
436
useWorkerFetch: boolean;
437
/** Canvas memory limit */
438
canvasMaxAreaInBytes: number;
439
/** Enable image caching */
440
enableImageCaching: boolean;
441
}
442
443
// Optimal performance configuration
444
const performanceConfig: PerformanceConfig = {
445
useOffscreenCanvas: FeatureTest.platform.isOffscreenCanvasSupported,
446
maxPageCache: 10,
447
useWorkerFetch: true,
448
canvasMaxAreaInBytes: 268435456, // 256MB
449
enableImageCaching: true
450
};
451
```