pdf_oxide 0.3.24

The fastest Rust PDF library with text extraction: 0.8ms mean, 100% pass rate on 3,830 PDFs. 5× faster than pdf_extract, 17× faster than oxidize_pdf. Extract, create, and edit PDFs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
# Stream API for PDF Oxide Node.js

## Overview

Phase 2.4 adds comprehensive Stream API support to PDF Oxide Node.js, enabling idiomatic Node.js streaming patterns for PDF operations. These readable streams handle backpressure automatically and integrate seamlessly with Node.js ecosystem tools.

## Key Features

✅ **Readable Streams** - Standard Node.js stream interface
✅ **Backpressure Handling** - Automatic flow control
✅ **Object Mode** - Streams emit objects, not buffers
✅ **Memory Efficient** - Streams results one at a time
✅ **Pipe-Compatible** - Works with `pipe()` and other stream transformers
✅ **Promise-Compatible** - Can be used with async/await
✅ **Error Handling** - Proper error propagation through streams

## The Three Streams

### 1. SearchStream

A readable stream that emits search results one at a time.

#### Basic Usage

```javascript
import { SearchStream, SearchManager } from 'pdf_oxide';

const doc = PdfDocument.open('document.pdf');
const searchManager = new SearchManager(doc);

// Create a stream to search for 'invoice'
const stream = new SearchStream(searchManager, 'invoice');

stream.on('data', (result) => {
  console.log(`Found on page ${result.pageIndex + 1}: ${result.text}`);
});

stream.on('end', () => {
  console.log('Search complete');
});
```

#### SearchStream Options

```javascript
// Page-specific search
new SearchStream(manager, 'keyword', {
  pageIndex: 0,           // Search only page 0
  caseSensitive: false,   // Case-insensitive
  wholeWords: false,      // Include partial matches
  maxResults: 100         // Limit results
});

// Document-wide search (default)
new SearchStream(manager, 'keyword');  // No pageIndex = search all pages
```

#### SearchResult Object

Each data event emits a SearchResult object:

```javascript
{
  text: string,                    // Matched text
  pageIndex: number,               // Zero-based page number
  position: number,                // Position within page
  boundingBox: {                   // Optional
    x: number,
    y: number,
    width: number,
    height: number
  }
}
```

#### Using with Pipes

```javascript
import { createReadStream, createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { Transform } from 'node:stream';

// Create a transform to format results
const formatter = new Transform({
  objectMode: true,
  transform(result, encoding, callback) {
    const line = `Page ${result.pageIndex + 1}: ${result.text}\n`;
    callback(null, line);
  }
});

// Pipe search results to file
await pipeline(
  new SearchStream(manager, 'invoice'),
  formatter,
  createWriteStream('search_results.txt')
);
```

#### Using with Promises

```javascript
import { pipeline } from 'node:stream/promises';
import { Writable } from 'node:stream';

// Collect all results
const results = [];
await pipeline(
  new SearchStream(manager, 'error'),
  new Writable({
    objectMode: true,
    write(result, encoding, callback) {
      results.push(result);
      callback();
    }
  })
);

console.log(`Found ${results.length} errors`);
```

---

### 2. ExtractionStream

A readable stream that emits extraction progress with extracted text for each page.

#### Basic Usage

```javascript
import { ExtractionStream, ExtractionManager } from 'pdf_oxide';

const doc = PdfDocument.open('document.pdf');
const extractionManager = new ExtractionManager(doc);

// Extract pages 0-10 as text
const stream = new ExtractionStream(extractionManager, 0, 10, 'text');

stream.on('data', (progress) => {
  const percent = Math.round(progress.progress * 100);
  console.log(`[${percent}%] Page ${progress.pageIndex + 1}: ${progress.extractedText.length} chars`);
});

stream.on('end', () => {
  console.log('Extraction complete');
});
```

#### Extraction Types

```javascript
// Plain text extraction (default)
new ExtractionStream(manager, 0, 10, 'text');

// Markdown extraction with structure
new ExtractionStream(manager, 0, 10, 'markdown');

// HTML extraction with formatting
new ExtractionStream(manager, 0, 10, 'html');
```

#### ExtractionProgress Object

Each data event emits an ExtractionProgress object:

```javascript
{
  pageIndex: number,           // Current page (0-indexed)
  totalPages: number,          // Total pages in range
  extractedText: string,       // Extracted content
  extractionType: string,      // 'text', 'markdown', or 'html'
  progress: number             // 0.0 to 1.0 completion
}
```

#### Visual Progress Indicator

```javascript
import blessed from 'blessed';

const screen = blessed.screen();
const progressBar = blessed.progressbar({
  parent: screen,
  top: 0,
  left: 0,
  width: '100%',
  height: 3
});

const stream = new ExtractionStream(extractionManager, 0, 100, 'markdown');

stream.on('data', (progress) => {
  progressBar.setProgress(progress.progress * 100);
});
```

#### Collecting All Extracted Text

```javascript
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';

const textCollector = [];

await pipeline(
  new ExtractionStream(manager, 0, 50, 'text'),
  new Transform({
    objectMode: true,
    transform(progress, encoding, callback) {
      textCollector.push(progress.extractedText);
      callback();
    }
  })
);

const allText = textCollector.join('\n---\n');
console.log(`Extracted ${allText.length} total characters`);
```

---

### 3. MetadataStream

A readable stream that emits page metadata (dimensions, fonts, images, rotation).

#### Basic Usage

```javascript
import { MetadataStream, RenderingManager } from 'pdf_oxide';

const doc = PdfDocument.open('document.pdf');
const renderingManager = new RenderingManager(doc);

// Get metadata for pages 0-10
const stream = new MetadataStream(renderingManager, 0, 10);

stream.on('data', (metadata) => {
  console.log(`Page ${metadata.pageIndex + 1}:`);
  console.log(`  Size: ${metadata.width} × ${metadata.height} points`);
  console.log(`  Fonts: ${metadata.fontCount}`);
  console.log(`  Images: ${metadata.imageCount}`);
});

stream.on('end', () => {
  console.log('Metadata retrieval complete');
});
```

#### PageMetadata Object

Each data event emits a PageMetadata object:

```javascript
{
  pageIndex: number,      // Zero-based page number
  width: number,          // Page width in points
  height: number,         // Page height in points
  fontCount: number,      // Embedded font count
  imageCount: number,     // Embedded image count
  rotation: number        // 0, 90, 180, or 270 degrees
}
```

#### Document Analysis

```javascript
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';

const stats = {
  totalImages: 0,
  totalFonts: 0,
  averageWidth: 0,
  averageHeight: 0,
  pageCount: 0
};

await pipeline(
  new MetadataStream(manager, 0, doc.pageCount),
  new Transform({
    objectMode: true,
    transform(metadata, encoding, callback) {
      stats.totalImages += metadata.imageCount;
      stats.totalFonts += metadata.fontCount;
      stats.averageWidth += metadata.width;
      stats.averageHeight += metadata.height;
      stats.pageCount++;
      callback();
    }
  })
);

stats.averageWidth /= stats.pageCount;
stats.averageHeight /= stats.pageCount;

console.log('Document Statistics:');
console.log(`  Pages: ${stats.pageCount}`);
console.log(`  Total images: ${stats.totalImages}`);
console.log(`  Total fonts: ${stats.totalFonts}`);
console.log(`  Average size: ${stats.averageWidth} × ${stats.averageHeight}`);
```

---

## Factory Functions

Convenient factory functions for creating streams:

```javascript
import {
  createSearchStream,
  createExtractionStream,
  createMetadataStream
} from 'pdf_oxide';

// These are equivalent to using constructors
const searchStream = createSearchStream(manager, 'keyword');
const extractionStream = createExtractionStream(manager, 0, 10, 'text');
const metadataStream = createMetadataStream(manager, 0, 10);
```

---

## Stream Event Handling

All streams support standard Node.js stream events:

```javascript
const stream = new SearchStream(manager, 'text');

// Data events
stream.on('data', (result) => {
  console.log('New result:', result);
});

// End event
stream.on('end', () => {
  console.log('Stream ended');
});

// Error events
stream.on('error', (error) => {
  console.error('Stream error:', error);
});

// Pause/resume
stream.on('pause', () => {
  console.log('Stream paused');
});

stream.on('resume', () => {
  console.log('Stream resumed');
});

// Close event
stream.on('close', () => {
  console.log('Stream closed');
});

// Drain event (backpressure)
stream.on('drain', () => {
  console.log('Internal buffer drained');
});
```

---

## Backpressure Handling

Streams automatically handle backpressure - the internal mechanism that prevents memory overflow when consuming streams faster than they're produced.

```javascript
import { createWriteStream } from 'node:fs';

const searchStream = new SearchStream(manager, 'data');
const fileStream = createWriteStream('output.jsonl');

// Pipe automatically handles backpressure
searchStream.pipe(fileStream);
```

Manual backpressure handling:

```javascript
const stream = new SearchStream(manager, 'keyword');
let keepReading = true;

stream.on('data', (result) => {
  const shouldContinue = process.stdout.write(JSON.stringify(result) + '\n');

  if (!shouldContinue) {
    console.log('Pausing due to backpressure...');
    stream.pause();
  }
});

process.stdout.on('drain', () => {
  console.log('Resuming after drain...');
  stream.resume();
});
```

---

## Advanced Patterns

### Combining Multiple Streams

```javascript
import { PassThrough } from 'node:stream';

// Create combined analysis
const combined = new PassThrough({ objectMode: true });

const searchResults = new SearchStream(searchManager, 'error');
const pageMetadata = new MetadataStream(renderingManager, 0, doc.pageCount);

// Merge both streams
searchResults.on('data', (result) => {
  combined.write({ type: 'search', data: result });
});

pageMetadata.on('data', (metadata) => {
  combined.write({ type: 'metadata', data: metadata });
});

searchResults.on('end', () => {
  pageMetadata.on('end', () => {
    combined.end();
  });
});

combined.on('data', (item) => {
  console.log(`${item.type}:`, item.data);
});
```

### Filtering Stream Results

```javascript
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';

const filterPages = new Transform({
  objectMode: true,
  transform(result, encoding, callback) {
    // Only emit results from pages 5 and beyond
    if (result.pageIndex >= 5) {
      callback(null, result);
    } else {
      callback();
    }
  }
});

await pipeline(
  new SearchStream(manager, 'keyword'),
  filterPages
);
```

### Rate Limiting

```javascript
import { Transform } from 'node:stream';

const rateLimiter = new Transform({
  objectMode: true,
  highWaterMark: 10,

  transform(result, encoding, callback) {
    setTimeout(() => {
      callback(null, result);
    }, 100); // 100ms delay per result
  }
});

const stream = new SearchStream(manager, 'keyword');

stream
  .pipe(rateLimiter)
  .on('data', (result) => {
    console.log('Processing:', result.text);
  });
```

---

## Error Handling

Proper error handling with streams:

```javascript
const stream = new SearchStream(manager, 'test');

stream.on('error', (error) => {
  console.error('Search stream error:', error.message);
  // Handle error - stream is destroyed
});

// Or with pipeline
import { pipeline } from 'node:stream/promises';

try {
  await pipeline(
    new ExtractionStream(manager, 0, 100),
    processStream,
    outputStream
  );
} catch (error) {
  console.error('Pipeline failed:', error);
}
```

---

## Performance Considerations

### Memory Efficiency

Streams process one item at a time, perfect for large result sets:

```javascript
// ❌ Memory intensive - loads all 100k results into memory
const allResults = manager.searchAll('keyword');

// ✅ Memory efficient - streams one result at a time
const stream = new SearchStream(manager, 'keyword');
stream.on('data', (result) => {
  // Process one result
});
```

### Controlling Flow

```javascript
const stream = new SearchStream(manager, 'keyword');
let processed = 0;

stream.on('data', (result) => {
  processed++;

  // Stop after 1000 results
  if (processed >= 1000) {
    stream.destroy();
  }
});
```

---

## Integration with Popular Libraries

### Using with database insertion

```javascript
import { pipeline } from 'node:stream/promises';
import { Transform } from 'node:stream';
import sqlite3 from 'sqlite3';

const db = new sqlite3.Database(':memory:');

await pipeline(
  new SearchStream(manager, 'invoice'),
  new Transform({
    objectMode: true,
    async transform(result, encoding, callback) {
      db.run(
        'INSERT INTO results (text, page, position) VALUES (?, ?, ?)',
        [result.text, result.pageIndex, result.position],
        callback
      );
    }
  })
);
```

### Using with Express response

```javascript
import express from 'express';
import { createSearchStream } from 'pdf_oxide';

const app = express();

app.get('/search/:term', (req, res) => {
  const stream = createSearchStream(manager, req.params.term);

  res.setHeader('Content-Type', 'application/x-ndjson');
  stream.pipe(res);

  stream.on('error', (error) => {
    res.status(500).json({ error: error.message });
  });
});
```

---

## Backward Compatibility

All streams are **purely additive** - existing APIs remain unchanged:

```javascript
// Original synchronous API still works
const results = manager.searchAll('keyword');

// New streaming API is optional
const stream = createSearchStream(manager, 'keyword');
stream.on('data', (result) => {
  console.log(result);
});
```

---

## References

- [Node.js Stream Documentation]https://nodejs.org/api/stream.html
- [Stream Handbook]https://github.com/substack/stream-handbook
- [Stream Backpressure Guide]https://nodejs.org/en/docs/guides/backpressuring-in-streams/