docx-handlebars 0.2.3

A Rust library for processing DOCX files with Handlebars templates, supporting WASM, Node.js, Deno, and browsers
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
# docx-handlebars

[![Crates.io](https://img.shields.io/crates/v/docx-handlebars.svg)](https://crates.io/crates/docx-handlebars)
[![Documentation](https://docs.rs/docx-handlebars/badge.svg)](https://docs.rs/docx-handlebars)
[![License](https://img.shields.io/crates/l/docx-handlebars.svg)](https://github.com/sail-sail/docx-handlebars#license)

[δΈ­ζ–‡ζ–‡ζ‘£](README_zh.md) | English

A Rust library for processing DOCX files with Handlebars templates, supporting multiple platforms:
- πŸ¦€ Rust native
- 🌐 WebAssembly (WASM)
- πŸ“¦ npm package
- 🟒 Node.js
- πŸ¦• Deno
- 🌍 Browser
- πŸ“‹ JSR (JavaScript Registry)

## Features

- βœ… **Smart Merging**: Automatically handles Handlebars syntax split by XML tags
- βœ… **DOCX Validation**: Built-in file format validation to ensure valid input files
- βœ… **Handlebars Support**: Full template engine with variables, conditionals, loops, and helper functions
- βœ… **Cross-platform**: Rust native + WASM support for multiple runtimes
- βœ… **TypeScript**: Complete type definitions and intelligent code completion
- βœ… **Zero Dependencies**: WASM binary with no external dependencies
- βœ… **Error Handling**: Detailed error messages and type-safe error handling

## Installation

### Rust

```bash
cargo add docx-handlebars
```

### npm

```bash
npm install docx-handlebars
```

### Deno

```typescript
import { render, init } from "jsr:@sail/docx-handlebars";
```

## Usage Examples

### Rust

```rust
use docx_handlebars::render_handlebars;
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Read DOCX template file
    let template_bytes = std::fs::read("template.docx")?;
    
    // Prepare data
    let data = json!({
        "name": "John Doe",
        "company": "ABC Technology Ltd.",
        "position": "Software Engineer",
        "projects": [
            {"name": "Project A", "status": "Completed"},
            {"name": "Project B", "status": "In Progress"}
        ],
        "has_bonus": true,
        "bonus_amount": 5000
    });
    
    // Render template
    let result = render_handlebars(template_bytes, &data)?;
    
    // Save result
    std::fs::write("output.docx", result)?;
    
    Ok(())
}
```

### JavaScript/TypeScript (Node.js)

```javascript
import { render, init } from 'docx-handlebars';
import fs from 'fs';

async function processTemplate() {
    // Initialize WASM module
    await init();
    
    // Read template file
    const templateBytes = fs.readFileSync('template.docx');
    
    // Prepare data
    const data = {
        name: "Jane Smith",
        company: "XYZ Tech Ltd.",
        position: "Senior Developer",
        projects: [
            { name: "E-commerce Platform", status: "Completed" },
            { name: "Mobile App", status: "In Development" }
        ],
        has_bonus: true,
        bonus_amount: 8000
    };
    
    // Render template
    const result = render(templateBytes, JSON.stringify(data));
    
    // Save result
    fs.writeFileSync('output.docx', new Uint8Array(result));
}

processTemplate().catch(console.error);
```

### Deno

```typescript
import { render, init } from "https://deno.land/x/docx_handlebars/mod.ts";

async function processTemplate() {
    // Initialize WASM module
    await init();
    
    // Read template file
    const templateBytes = await Deno.readFile("template.docx");
    
    // Prepare data
    const data = {
        name: "Alice Johnson",
        department: "R&D Department",
        projects: [
            { name: "AI Customer Service", status: "Live" },
            { name: "Data Visualization Platform", status: "In Development" }
        ]
    };
    
    // Render template
    const result = render(templateBytes, JSON.stringify(data));
    
    // Save result
    await Deno.writeFile("output.docx", new Uint8Array(result));
}

if (import.meta.main) {
    await processTemplate();
}
```

### Browser

```html
<!DOCTYPE html>
<html>
<head>
    <title>DOCX Handlebars Example</title>
</head>
<body>
    <input type="file" id="fileInput" accept=".docx">
    <button onclick="processFile()">Process Template</button>
    
    <script type="module">
        import { render, init } from './pkg/docx_handlebars.js';
        
        // Initialize WASM
        await init();
        
        window.processFile = async function() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            
            if (!file) return;
            
            const arrayBuffer = await file.arrayBuffer();
            const templateBytes = new Uint8Array(arrayBuffer);
            
            const data = {
                name: "John Doe",
                company: "Example Company"
            };
            
            try {
                const result = render(templateBytes, JSON.stringify(data));
                
                // Download result
                const blob = new Blob([new Uint8Array(result)], {
                    type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'processed.docx';
                a.click();
            } catch (error) {
                console.error('Processing failed:', error);
            }
        };
    </script>
</body>
</html>
```

## Template Syntax

### Basic Variable Substitution

```handlebars
Employee Name: {{name}}
Company: {{company}}
Position: {{position}}
```

### Conditional Rendering

```handlebars
{{#if has_bonus}}
Bonus: ${{bonus_amount}}
{{else}}
No bonus
{{/if}}

{{#unless is_intern}}
Full-time employee
{{/unless}}
```

### Loop Rendering

```handlebars
Project Experience:
{{#each projects}}
- {{name}}: {{description}} ({{status}})
{{/each}}

Skills:
{{#each skills}}
{{@index}}. {{this}}
{{/each}}
```

### Helper Functions

Built-in helper functions:

```handlebars
{{upper name}}           <!-- Convert to uppercase -->
{{lower company}}        <!-- Convert to lowercase -->
{{len projects}}         <!-- Array length -->
{{#if (eq status "completed")}}Completed{{/if}}    <!-- Equality comparison -->
{{#if (gt score 90)}}Excellent{{/if}}              <!-- Greater than comparison -->
{{#if (lt age 30)}}Young{{/if}}                    <!-- Less than comparison -->
```

### Complex Example

```handlebars
=== Employee Report ===

Basic Information:
Name: {{employee.name}}
Department: {{employee.department}}
Position: {{employee.position}}
Hire Date: {{employee.hire_date}}

{{#if employee.has_bonus}}
πŸ’° Bonus: ${{employee.bonus_amount}}
{{/if}}

Project Experience ({{len projects}} total):
{{#each projects}}
{{@index}}. {{name}}
   Description: {{description}}
   Status: {{status}}
   Team Size: {{team_size}} people
   
{{/each}}

Skills Assessment:
{{#each skills}}
- {{name}}: {{level}}/10 ({{years}} years experience)
{{/each}}

To delete an entire table row, simply add the following to any cell in that row:
{{removeTableRow}}

{{#if (gt performance.score 90)}}
πŸŽ‰ Performance Rating: Excellent
{{else if (gt performance.score 80)}}
πŸ‘ Performance Rating: Good
{{else}}
πŸ“ˆ Performance Rating: Needs Improvement
{{/if}}

Image:
{{img base64_image_data [width] [height]}}
  only height: {{img base64 "" 200}}
  only width: {{img base64 300}}
  no width/height: {{img base64}}
  both width/height: {{img base64 300 200}}
```

## Error Handling

The library provides detailed error types and messages:

### Rust

```rust
use docx_handlebars::{render_handlebars, DocxError};

match render_handlebars(template_bytes, &data) {
    Ok(result) => {
        println!("Processing successful!");
        std::fs::write("output.docx", result)?;
    }
    Err(e) => match e.downcast_ref::<DocxError>() {
        Some(DocxError::InvalidZipFormat) => {
            eprintln!("Error: File is not a valid ZIP/DOCX format");
        }
        _ => {
            eprintln!("Other error: {}", e);
        }
    }
}
```

### JavaScript/TypeScript

```javascript
try {
    const result = render(templateBytes, JSON.stringify(data));
    console.log('Processing successful!');
} catch (error) {
    console.error('Processing failed:', error);
}
```

## Build and Development

### Build WASM Packages

```bash
# Build all targets
npm run build

# Or build separately
npm run build:web    # Browser version
npm run build:npm    # Node.js version 
npm run build:jsr    # Deno version
```

### Run Examples

```bash
# Rust example
cargo run --example rust_example

# Node.js example
node examples/node_example.js

# Deno example  
deno run --allow-read --allow-write examples/deno_example.ts

# Browser example
cd tests/npm_test
node serve.js
# Then open http://localhost:8080 in your browser
# Select examples/template.docx file to test
```

## Technical Features

### Smart Merging Algorithm

The core innovation of this library is the intelligent merging of Handlebars syntax that has been split by XML tags. In DOCX files, when users input template syntax, Word may split it into multiple XML tags.

### File Validation

Built-in DOCX file validation ensures input file integrity:

1. **ZIP Format Validation**: Check file signature and structure
2. **DOCX Structure Validation**: Ensure required files are present
   - `[Content_Types].xml`
   - `_rels/.rels` 
   - `word/document.xml`
3. **MIME Type Validation**: Verify correct content types

## Performance and Compatibility

- **Zero Copy**: Efficient memory management between Rust and WASM
- **Streaming Processing**: Suitable for handling large DOCX files
- **Cross-platform**: Support for Windows, macOS, Linux, Web
- **Modern Browsers**: Support for all modern browsers that support WASM

## License

This project is licensed under the MIT License - see the [LICENSE-MIT](LICENSE-MIT) file for details.

## Support

- πŸ“š [Documentation]https://docs.rs/docx-handlebars
- πŸ› [Issue Tracker]https://github.com/sail-sail/docx-handlebars/issues
- πŸ’¬ [Discussions]https://github.com/sail-sail/docx-handlebars/discussions

---

<div align="center">
  <p>
    <strong>docx-handlebars</strong> - Making DOCX template processing simple and efficient
  </p>
  <p>
    <a href="https://github.com/sail-sail/docx-handlebars">⭐ Star the project</a>
    Β·
    <a href="https://github.com/sail-sail/docx-handlebars/issues">πŸ› Report issues</a>
    Β·
    <a href="https://github.com/sail-sail/docx-handlebars/discussions">πŸ’¬ Join discussions</a>
  </p>
</div>