pdf_oxide 0.3.2

The Complete PDF Toolkit: extract, create, and edit PDFs. Rust core with bindings for Python, Node, WASM, Go, and more.
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
# C# Phase 2 API Examples - PDF Creation and Editing

This document provides practical examples for using the Phase 2 C# bindings for pdf_oxide.

## Table of Contents

1. [PDF Creation]#pdf-creation
2. [Document Editing]#document-editing
3. [Page Access]#page-access
4. [Advanced Scenarios]#advanced-scenarios

---

## PDF Creation

### Creating PDFs from Different Formats

#### From Markdown

```csharp
using System;
using PdfOxide.Core;

// Create a PDF from Markdown
var markdown = @"# Welcome to PDF Oxide

This is a **bold** text and this is *italic*.

## Features

- Text extraction
- PDF creation
- Document editing

```";

using (var pdf = Pdf.FromMarkdown(markdown))
{
    pdf.Save("output.pdf");
    Console.WriteLine($"Created PDF with {pdf.PageCount} pages");
}
```

#### From HTML

```csharp
using System;
using PdfOxide.Core;

var html = @"
<html>
    <head><title>My Document</title></head>
    <body>
        <h1>Heading 1</h1>
        <p>This is a paragraph with <b>bold</b> and <i>italic</i> text.</p>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
    </body>
</html>";

using (var pdf = Pdf.FromHtml(html))
{
    pdf.Save("from_html.pdf");
}
```

#### From Plain Text

```csharp
using System;
using PdfOxide.Core;

var text = @"This is a simple text document.
It will be converted to PDF.
Multiple lines are preserved.

This is a new paragraph.";

using (var pdf = Pdf.FromText(text))
{
    pdf.Save("from_text.pdf");
    Console.WriteLine($"Page count: {pdf.PageCount}");
}
```

### Saving PDFs to Different Destinations

#### Save to File

```csharp
using (var pdf = Pdf.FromMarkdown("# Hello World"))
{
    pdf.Save("document.pdf");
}
```

#### Save to Byte Array

```csharp
using (var pdf = Pdf.FromMarkdown("# Hello World"))
{
    byte[] pdfBytes = pdf.SaveToBytes();
    System.IO.File.WriteAllBytes("output.pdf", pdfBytes);
}
```

#### Save to Stream

```csharp
using (var pdf = Pdf.FromMarkdown("# Hello World"))
using (var stream = System.IO.File.Create("output.pdf"))
{
    pdf.SaveToStream(stream);
}
```

#### Async Save

```csharp
using System;
using System.Threading.Tasks;
using PdfOxide.Core;

public async Task SavePdfAsync(string content)
{
    using (var pdf = Pdf.FromMarkdown(content))
    {
        await pdf.SaveAsync("document.pdf");
        Console.WriteLine("PDF saved asynchronously");
    }
}

// Usage
await SavePdfAsync("# Async Example");
```

---

## Document Editing

### Opening and Modifying PDFs

#### Edit Metadata

```csharp
using System;
using PdfOxide.Core;

using (var editor = DocumentEditor.Open("existing.pdf"))
{
    Console.WriteLine($"Pages: {editor.PageCount}");
    
    // Modify metadata
    editor.Title = "Updated Title";
    editor.Author = "John Doe";
    editor.Subject = "PDF Editing Example";
    
    Console.WriteLine($"Modified: {editor.IsModified}");
    
    // Save changes
    editor.Save("edited.pdf");
}
```

#### Check Modification Status

```csharp
using (var editor = DocumentEditor.Open("document.pdf"))
{
    if (editor.IsModified)
    {
        Console.WriteLine("Document has unsaved changes");
        editor.Save("document.pdf");
    }
    else
    {
        Console.WriteLine("Document is unchanged");
    }
}
```

#### Read Document Information

```csharp
using (var editor = DocumentEditor.Open("document.pdf"))
{
    Console.WriteLine($"Source: {editor.SourcePath}");
    
    var (major, minor) = editor.Version;
    Console.WriteLine($"PDF Version: {major}.{minor}");
    
    Console.WriteLine($"Pages: {editor.PageCount}");
    Console.WriteLine($"Title: {editor.Title ?? "(not set)"}");
    Console.WriteLine($"Author: {editor.Author ?? "(not set)"}");
    Console.WriteLine($"Subject: {editor.Subject ?? "(not set)"}");
}
```

#### Update All Metadata Fields

```csharp
using (var editor = DocumentEditor.Open("input.pdf"))
{
    editor.Title = "New Title";
    editor.Author = "Jane Smith";
    editor.Subject = "Updated Subject";
    
    editor.Save("output_with_metadata.pdf");
}
```

---

## Page Access

### Getting Page Information

#### Page Dimensions

```csharp
using (var editor = DocumentEditor.Open("document.pdf"))
{
    for (int i = 0; i < editor.PageCount; i++)
    {
        // Page access would be extended in Phase 3
        // For now, we can access through DocumentEditor
        Console.WriteLine($"Page {i}: Processing...");
    }
}
```

#### Working with Multiple Pages

```csharp
using System;
using PdfOxide.Core;

using (var editor = DocumentEditor.Open("multi_page.pdf"))
{
    int pageCount = editor.PageCount;
    Console.WriteLine($"Total pages: {pageCount}");
    
    // Create a new PDF from the same content with updated metadata
    editor.Title = $"Updated - {DateTime.Now:yyyy-MM-dd}";
    editor.Author = "Processing System";
    
    editor.Save("processed.pdf");
}
```

---

## Advanced Scenarios

### Batch Processing Multiple PDFs

```csharp
using System;
using System.IO;
using PdfOxide.Core;

public class PdfBatchProcessor
{
    public void ProcessPdfsInDirectory(string directory)
    {
        var files = Directory.GetFiles(directory, "*.pdf");
        
        foreach (var file in files)
        {
            using (var editor = DocumentEditor.Open(file))
            {
                // Add processing metadata
                editor.Author = "Batch Processor";
                editor.Subject = $"Processed on {DateTime.Now:yyyy-MM-dd}";
                
                string outputPath = Path.Combine(directory, 
                    Path.GetFileNameWithoutExtension(file) + "_processed.pdf");
                
                editor.Save(outputPath);
                Console.WriteLine($"Processed: {file}");
            }
        }
    }
}

// Usage
var processor = new PdfBatchProcessor();
processor.ProcessPdfsInDirectory(@"C:\Documents\PDFs");
```

### Convert and Merge Workflows

```csharp
using System;
using System.Collections.Generic;
using PdfOxide.Core;

public class PdfConverter
{
    public void ConvertMarkdownToPdf(string markdownPath, string outputPath)
    {
        string markdown = System.IO.File.ReadAllText(markdownPath);
        
        using (var pdf = Pdf.FromMarkdown(markdown))
        {
            pdf.Save(outputPath);
            Console.WriteLine($"Converted: {markdownPath} -> {outputPath}");
        }
    }
    
    public void ConvertHtmlToPdf(string htmlPath, string outputPath)
    {
        string html = System.IO.File.ReadAllText(htmlPath);
        
        using (var pdf = Pdf.FromHtml(html))
        {
            pdf.Save(outputPath);
            Console.WriteLine($"Converted: {htmlPath} -> {outputPath}");
        }
    }
}

// Usage
var converter = new PdfConverter();
converter.ConvertMarkdownToPdf("document.md", "document.pdf");
converter.ConvertHtmlToPdf("webpage.html", "webpage.pdf");
```

### Error Handling

```csharp
using System;
using PdfOxide.Core;
using PdfOxide.Exceptions;

try
{
    using (var editor = DocumentEditor.Open("document.pdf"))
    {
        editor.Title = "Updated";
        editor.Save("output.pdf");
    }
}
catch (PdfIoException ex)
{
    Console.WriteLine($"File I/O error: {ex.Message}");
}
catch (PdfParseException ex)
{
    Console.WriteLine($"PDF parse error: {ex.Message}");
}
catch (PdfException ex)
{
    Console.WriteLine($"PDF error: {ex.Message}");
}
```

### Async Workflow

```csharp
using System;
using System.Threading.Tasks;
using PdfOxide.Core;

public class AsyncPdfProcessor
{
    public async Task ProcessPdfAsync(string inputPath, string outputPath)
    {
        // Create from Markdown
        var markdown = await System.IO.File.ReadAllTextAsync(inputPath);
        
        using (var pdf = Pdf.FromMarkdown(markdown))
        {
            await pdf.SaveAsync(outputPath);
            Console.WriteLine("Processing completed");
        }
    }
    
    public async Task EditPdfAsync(string inputPath, string outputPath)
    {
        using (var editor = DocumentEditor.Open(inputPath))
        {
            editor.Title = "Async Processed";
            editor.Author = "Async Processor";
            
            await editor.SaveAsync(outputPath);
            Console.WriteLine("Editing completed");
        }
    }
}

// Usage
var processor = new AsyncPdfProcessor();
await processor.ProcessPdfAsync("input.md", "output.pdf");
await processor.EditPdfAsync("document.pdf", "edited.pdf");
```

### Stream-Based Processing

```csharp
using System;
using System.IO;
using PdfOxide.Core;

public class StreamProcessor
{
    public void ConvertStreamToPdf(Stream inputStream, Stream outputStream)
    {
        // Read from input stream
        using (var reader = new StreamReader(inputStream))
        {
            string content = reader.ReadToEnd();
            
            // Create PDF
            using (var pdf = Pdf.FromText(content))
            {
                // Save to output stream
                pdf.SaveToStream(outputStream);
            }
        }
    }
    
    public void EditFromStream(Stream inputStream, Stream outputStream)
    {
        // Read PDF from stream
        using (var editor = DocumentEditor.Open(inputStream))
        {
            editor.Title = "Stream Processed";
            
            // Note: Future enhancement - save to stream support
            string tempFile = Path.GetTempFileName();
            editor.Save(tempFile);
            
            // Copy to output stream
            using (var fileStream = File.OpenRead(tempFile))
            {
                fileStream.CopyTo(outputStream);
            }
            
            File.Delete(tempFile);
        }
    }
}
```

---

## Summary

Phase 2 provides:

✅ **PDF Creation** - From Markdown, HTML, and plain text
✅ **Document Editing** - Metadata modification and state tracking
✅ **Page Access** - Page information and properties
✅ **Async Support** - Asynchronous save operations
✅ **Error Handling** - Typed exception hierarchy
✅ **Stream Support** - Work with files and memory streams

### Key Patterns

- **Creating PDFs**: Use static factory methods (`Pdf.FromMarkdown()`, etc.)
- **Editing PDFs**: Use `DocumentEditor.Open()` and save changes
- **Async Operations**: Use `SaveAsync()` with `CancellationToken`
- **Resource Management**: Always use `using` statements
- **Error Handling**: Catch specific exception types

### Next Steps (Phase 3+)

- DOM element access and manipulation
- Text finding and replacement
- Image handling
- Annotation support
- Advanced page operations (add, remove, reorder)