duc2pdf 3.4.1

A library to convert DUC files to PDF format.
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
use std::collections::HashMap;
use wasm_bindgen::prelude::*;

pub mod builder;

// Initialize logger for WASM
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen(start)]
pub fn init_logger() {
    console_log::init_with_level(log::Level::Info).expect("Failed to initialize logger");
}
pub mod scaling;
pub mod streaming;
pub mod utils;

mod error_handling;

// Coordinate system constants
pub const MAX_COORDINATE_MM: f64 = 4_800.0; // Safe maximum coordinate in mm
pub const MIN_PRECISION_MM: f64 = 50.0; // Minimum precision in mm
pub const PDF_USER_UNIT: f32 = 72.0 / 25.4; // Convert mm to PDF units (1 inch = 25.4mm = 72 points)

fn normalize_background_color(color: Option<String>) -> Option<String> {
    color.and_then(|value| {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            None
        } else if trimmed.eq_ignore_ascii_case("transparent") {
            None
        } else {
            Some(trimmed.to_string())
        }
    })
}

#[derive(Debug)]
pub enum ConversionMode {
    Plot,
    Crop {
        offset_x: f64,
        offset_y: f64,
        width: Option<f64>, // Optional crop width in mm (None = use full viewport)
        height: Option<f64>, // Optional crop height in mm (None = use full viewport)
    },
}

#[derive(Debug)]
pub struct ConversionOptions {
    pub mode: ConversionMode,
    pub scale: Option<f64>, // Optional scale factor (e.g., 1.0/50.0, 1.0/10.0)
    pub background_color: Option<String>,
    pub metadata_title: Option<String>,
    pub metadata_author: Option<String>,
    pub metadata_subject: Option<String>,
}

impl Default for ConversionOptions {
    fn default() -> Self {
        Self {
            mode: ConversionMode::Plot,
            scale: None, // No scale by default, will auto-scale if needed
            background_color: None,
            metadata_title: None,
            metadata_author: None,
            metadata_subject: None,
        }
    }
}

#[derive(Debug)]
pub enum ConversionError {
    InvalidDucData(String),
    CoordinateOutOfBounds(f64, f64),
    ScaleExceedsBounds(f64, f64, f64), // (x, y, scale) - when user provided scale still exceeds bounds
    PrecisionTooHigh(f64),
    PdfGenerationError(String),
    ResourceLoadError(String),
}

impl std::fmt::Display for ConversionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConversionError::InvalidDucData(msg) => write!(f, "Invalid DUC data: {}", msg),
            ConversionError::CoordinateOutOfBounds(x, y) => {
                write!(
                    f,
                    "Coordinate ({}, {}) exceeds safe bounds of ±{}mm",
                    x, y, MAX_COORDINATE_MM
                )
            }
            ConversionError::ScaleExceedsBounds(x, y, scale) => {
                write!(f, "Coordinate ({}, {}) with user-provided scale {} still exceeds safe bounds of ±{}mm", x, y, scale, MAX_COORDINATE_MM)
            }
            ConversionError::PrecisionTooHigh(precision) => {
                write!(
                    f,
                    "Precision {} exceeds minimum allowed precision of {}mm",
                    precision, MIN_PRECISION_MM
                )
            }
            ConversionError::PdfGenerationError(msg) => write!(f, "PDF generation error: {}", msg),
            ConversionError::ResourceLoadError(msg) => write!(f, "Resource loading error: {}", msg),
        }
    }
}

impl std::error::Error for ConversionError {}

pub type ConversionResult<T> = Result<T, ConversionError>;

/// Validates coordinates are within safe bounds with optional scaling
pub fn validate_coordinates_with_scale(
    x: f64,
    y: f64,
    scale: Option<f64>,
) -> ConversionResult<f64> {
    let scaled_x = x * scale.unwrap_or(1.0);
    let scaled_y = y * scale.unwrap_or(1.0);

    if scaled_x.abs() > MAX_COORDINATE_MM || scaled_y.abs() > MAX_COORDINATE_MM {
        if scale.is_some() {
            // User provided scale but it still exceeds bounds - this is an error
            return Err(ConversionError::ScaleExceedsBounds(x, y, scale.unwrap()));
        } else {
            // No scale provided, calculate required scale to fit within bounds
            let max_coord = x.abs().max(y.abs());
            let required_scale = MAX_COORDINATE_MM / max_coord * 0.95; // 5% safety margin
            return Ok(required_scale);
        }
    }

    // Coordinates are within bounds
    Ok(scale.unwrap_or(1.0))
}

/// Calculate bounding box for DUC data in millimeters
pub fn calculate_bounding_box(data: &duc::types::ExportedDataState) -> (f64, f64, f64, f64) {
    if data.elements.is_empty() {
        return (0.0, 0.0, 0.0, 0.0);
    }

    let mut min_x = f64::MAX;
    let mut min_y = f64::MAX;
    let mut max_x = f64::MIN;
    let mut max_y = f64::MIN;

    for element_wrapper in &data.elements {
        let base = match &element_wrapper.element {
            duc::types::DucElementEnum::DucRectangleElement(elem) => &elem.base,
            duc::types::DucElementEnum::DucPolygonElement(elem) => &elem.base,
            duc::types::DucElementEnum::DucEllipseElement(elem) => &elem.base,
            duc::types::DucElementEnum::DucEmbeddableElement(elem) => &elem.base,
            duc::types::DucElementEnum::DucPdfElement(elem) => &elem.base,
            duc::types::DucElementEnum::DucTableElement(elem) => &elem.base,
            duc::types::DucElementEnum::DucImageElement(elem) => &elem.base,
            duc::types::DucElementEnum::DucTextElement(elem) => &elem.base,
            duc::types::DucElementEnum::DucLinearElement(elem) => &elem.linear_base.base,
            duc::types::DucElementEnum::DucArrowElement(elem) => &elem.linear_base.base,
            duc::types::DucElementEnum::DucFreeDrawElement(elem) => &elem.base,
            duc::types::DucElementEnum::DucFrameElement(elem) => &elem.stack_element_base.base,
            duc::types::DucElementEnum::DucPlotElement(elem) => &elem.stack_element_base.base,
            duc::types::DucElementEnum::DucDocElement(elem) => &elem.base,
            duc::types::DucElementEnum::DucModelElement(elem) => &elem.base,
        };

        // Assume all coordinates are already in millimeters
        let (x_mm, y_mm, width_mm, height_mm) = (base.x, base.y, base.width, base.height);

        min_x = min_x.min(x_mm);
        min_y = min_y.min(y_mm);
        max_x = max_x.max(x_mm + width_mm);
        max_y = max_y.max(y_mm + height_mm);
    }

    (min_x, min_y, max_x - min_x, max_y - min_y)
}

/// Calculate required scale to fit content within safe bounds
pub fn calculate_required_scale(
    data: &duc::types::ExportedDataState,
    crop_offset: Option<(f64, f64)>,
) -> f64 {
    let (min_x, min_y, width, height) = calculate_bounding_box(data);

    // Apply offset if cropping - assume coordinates are already in millimeters
    let (effective_min_x, effective_min_y) = if let Some((offset_x_mm, offset_y_mm)) = crop_offset {
        // With offset, we're essentially moving the viewport, so adjust the bounding box accordingly
        (min_x - offset_x_mm, min_y - offset_y_mm)
    } else {
        (min_x, min_y)
    };

    let max_x = effective_min_x + width;
    let max_y = effective_min_y + height;

    // Find the maximum coordinate in any direction from the DUC content
    let max_coord_from_content = effective_min_x
        .abs()
        .max(effective_min_y.abs())
        .max(max_x.abs())
        .max(max_y.abs());

    // CRITICAL: Always check coordinate limits
    if max_coord_from_content <= MAX_COORDINATE_MM {
        return 1.0; // No scaling needed for content
    }

    // Calculate scale with 5% safety margin to ensure coordinates stay within limits
    MAX_COORDINATE_MM / max_coord_from_content * 0.95
}

/// Calculate required scale to fit both content AND crop dimensions within safe bounds
pub fn calculate_required_scale_with_crop_dimensions(
    data: &duc::types::ExportedDataState,
    crop_offset: Option<(f64, f64)>,
    crop_width: Option<f64>,
    crop_height: Option<f64>,
) -> f64 {
    // First, calculate scale based on content
    let content_scale = calculate_required_scale(data, crop_offset);

    // Then, calculate scale based on crop dimensions if provided
    let crop_scale = if let (Some(width), Some(height)) = (crop_width, crop_height) {
        // The crop dimensions define the viewport size, so we need to ensure they fit within PDF bounds
        let max_crop_dimension = width.max(height);

        if max_crop_dimension <= MAX_COORDINATE_MM {
            None // No scaling needed for crop dimensions
        } else {
            Some(MAX_COORDINATE_MM / max_crop_dimension * 0.95) // 5% safety margin
        }
    } else {
        None // No crop dimensions to consider
    };

    // Use the more restrictive scale (smaller value) to ensure both content and crop dimensions fit
    match crop_scale {
        Some(crop_scale) => content_scale.min(crop_scale),
        None => content_scale,
    }
}

/// Validates coordinates are within safe bounds
pub fn validate_coordinates(x: f64, y: f64) -> ConversionResult<()> {
    if x.abs() > MAX_COORDINATE_MM || y.abs() > MAX_COORDINATE_MM {
        return Err(ConversionError::CoordinateOutOfBounds(x, y));
    }
    Ok(())
}

/// Validates precision is above minimum threshold
pub fn validate_precision(precision: f64) -> ConversionResult<()> {
    if precision < MIN_PRECISION_MM {
        return Err(ConversionError::PrecisionTooHigh(precision));
    }
    Ok(())
}

/// Main conversion function with options
pub fn convert_duc_to_pdf_with_options(
    duc_data: &[u8],
    options: ConversionOptions,
) -> ConversionResult<Vec<u8>> {
    convert_duc_to_pdf_with_fonts_and_options(duc_data, options, HashMap::new())
}

/// Main conversion function with options and custom font data
pub fn convert_duc_to_pdf_with_fonts_and_options(
    duc_data: &[u8],
    options: ConversionOptions,
    font_data: HashMap<String, Vec<u8>>,
) -> ConversionResult<Vec<u8>> {
    let mut normalized_options = options;
    normalized_options.background_color =
        normalize_background_color(normalized_options.background_color);

    let exported_data =
        duc::parse::parse(duc_data).map_err(|e| ConversionError::InvalidDucData(e.to_string()))?;

    builder::DucToPdfBuilder::new(exported_data, normalized_options, font_data)?.build()
}

pub fn convert_exported_data_to_pdf_with_fonts_and_options(
    exported_data: duc::types::ExportedDataState,
    options: ConversionOptions,
    font_data: HashMap<String, Vec<u8>>,
) -> ConversionResult<Vec<u8>> {
    let mut normalized_options = options;
    normalized_options.background_color =
        normalize_background_color(normalized_options.background_color);

    builder::DucToPdfBuilder::new(exported_data, normalized_options, font_data)?.build()
}

/// WASM binding for the main conversion function
#[wasm_bindgen]
pub fn convert_duc_to_pdf_rs(duc_data: &[u8]) -> Vec<u8> {
    match convert_duc_to_pdf_with_options(duc_data, ConversionOptions::default()) {
        Ok(pdf_bytes) => pdf_bytes,
        Err(e) => {
            // Log error with context
            error_handling::log_error_details(
                &e,
                duc_data.len(),
                "Standard conversion (default options)",
            );

            // Create structured error info and convert to WASM bytes
            let error_info = error_handling::create_error_info(&e, duc_data.len(), None);
            error_handling::error_to_wasm_bytes(&error_info)
        }
    }
}

/// WASM binding for standard conversion with an explicit manual drawing scale.
#[wasm_bindgen]
pub fn convert_duc_to_pdf_with_scale_wasm(duc_data: &[u8], scale: f64) -> Vec<u8> {
    let options = ConversionOptions {
        scale: Some(scale),
        ..Default::default()
    };

    match convert_duc_to_pdf_with_options(duc_data, options) {
        Ok(pdf_bytes) => pdf_bytes,
        Err(e) => {
            error_handling::log_error_details(&e, duc_data.len(), "Standard conversion with scale");
            let options = ConversionOptions {
                scale: Some(scale),
                ..Default::default()
            };
            let error_info = error_handling::create_error_info(&e, duc_data.len(), Some(&options));
            error_handling::error_to_wasm_bytes(&error_info)
        }
    }
}

/// Conversion function with crop mode
pub fn convert_duc_to_pdf_crop(
    duc_data: &[u8],
    offset_x: f64,
    offset_y: f64,
) -> ConversionResult<Vec<u8>> {
    convert_duc_to_pdf_crop_with_options(duc_data, offset_x, offset_y, None, None, None, None)
}

/// Conversion function with crop mode and specific dimensions
pub fn convert_duc_to_pdf_crop_with_dimensions(
    duc_data: &[u8],
    offset_x: f64,
    offset_y: f64,
    width: f64,
    height: f64,
) -> ConversionResult<Vec<u8>> {
    convert_duc_to_pdf_crop_with_options(
        duc_data,
        offset_x,
        offset_y,
        Some(width),
        Some(height),
        None,
        None,
    )
}

pub fn convert_duc_to_pdf_crop_with_options(
    duc_data: &[u8],
    offset_x: f64,
    offset_y: f64,
    width: Option<f64>,
    height: Option<f64>,
    background_color: Option<String>,
    scale: Option<f64>,
) -> ConversionResult<Vec<u8>> {
    let options = ConversionOptions {
        mode: ConversionMode::Crop {
            offset_x,
            offset_y,
            width,
            height,
        },
        scale,
        background_color,
        ..Default::default()
    };
    convert_duc_to_pdf_with_options(duc_data, options)
}

/// WASM binding for crop conversion
#[wasm_bindgen]
pub fn convert_duc_to_pdf_crop_wasm(
    duc_data: &[u8],
    offset_x: f64,
    offset_y: f64,
    width: Option<f64>,
    height: Option<f64>,
    background_color: Option<String>,
) -> Vec<u8> {
    // Validate basic inputs first
    if let Err(validation_error) = error_handling::validate_basic_inputs(
        duc_data,
        Some(offset_x),
        Some(offset_y),
        width,
        height,
    ) {
        let error_info = error_handling::WasmErrorInfo {
            error: validation_error.clone(),
            error_type: "ValidationError".to_string(),
            details: validation_error,
            duc_data_length: duc_data.len(),
            conversion_context: None,
        };
        return error_handling::error_to_wasm_bytes(&error_info);
    }

    let normalized_background = normalize_background_color(background_color);

    match convert_duc_to_pdf_crop_with_options(
        duc_data,
        offset_x,
        offset_y,
        width,
        height,
        normalized_background.clone(),
        None,
    ) {
        Ok(pdf_bytes) => pdf_bytes,
        Err(e) => {
            // Log error with context and crop details
            error_handling::log_error_details(&e, duc_data.len(), "Crop conversion");
            error_handling::log_crop_details(offset_x, offset_y, width, height);

            // Create structured error info with crop context
            let crop_options = ConversionOptions {
                mode: ConversionMode::Crop {
                    offset_x,
                    offset_y,
                    width,
                    height,
                },
                background_color: normalized_background,
                ..Default::default()
            };
            let error_info =
                error_handling::create_error_info(&e, duc_data.len(), Some(&crop_options));
            error_handling::error_to_wasm_bytes(&error_info)
        }
    }
}

/// WASM binding for crop conversion with explicit manual drawing scale.
#[wasm_bindgen]
pub fn convert_duc_to_pdf_crop_scaled_wasm(
    duc_data: &[u8],
    offset_x: f64,
    offset_y: f64,
    width: Option<f64>,
    height: Option<f64>,
    background_color: Option<String>,
    scale: f64,
) -> Vec<u8> {
    if let Err(validation_error) = error_handling::validate_basic_inputs(
        duc_data,
        Some(offset_x),
        Some(offset_y),
        width,
        height,
    ) {
        let error_info = error_handling::WasmErrorInfo {
            error: validation_error.clone(),
            error_type: "ValidationError".to_string(),
            details: validation_error,
            duc_data_length: duc_data.len(),
            conversion_context: None,
        };
        return error_handling::error_to_wasm_bytes(&error_info);
    }

    let normalized_background = normalize_background_color(background_color);

    match convert_duc_to_pdf_crop_with_options(
        duc_data,
        offset_x,
        offset_y,
        width,
        height,
        normalized_background.clone(),
        Some(scale),
    ) {
        Ok(pdf_bytes) => pdf_bytes,
        Err(e) => {
            error_handling::log_error_details(&e, duc_data.len(), "Crop conversion with scale");
            error_handling::log_crop_details(offset_x, offset_y, width, height);

            let crop_options = ConversionOptions {
                mode: ConversionMode::Crop {
                    offset_x,
                    offset_y,
                    width,
                    height,
                },
                scale: Some(scale),
                background_color: normalized_background,
                ..Default::default()
            };
            let error_info =
                error_handling::create_error_info(&e, duc_data.len(), Some(&crop_options));
            error_handling::error_to_wasm_bytes(&error_info)
        }
    }
}

/// Deserialize a JS font map (Map<string, Uint8Array>) into a Rust HashMap
fn deserialize_font_map(font_map_js: JsValue) -> HashMap<String, Vec<u8>> {
    let mut fonts = HashMap::new();
    if font_map_js.is_undefined() || font_map_js.is_null() {
        return fonts;
    }

    let entries = js_sys::try_iter(&font_map_js).ok().flatten();

    if let Some(iter) = entries {
        for entry_result in iter {
            if let Ok(entry) = entry_result {
                let pair = js_sys::Array::from(&entry);
                if pair.length() == 2 {
                    let key = pair.get(0);
                    let value = pair.get(1);
                    if let Some(family) = key.as_string() {
                        let bytes = js_sys::Uint8Array::new(&value);
                        fonts.insert(family, bytes.to_vec());
                    }
                }
            }
        }
    }
    fonts
}

fn deserialize_exported_data(
    exported_data_js: JsValue,
) -> Result<duc::types::ExportedDataState, String> {
    serde_wasm_bindgen::from_value(exported_data_js)
        .map_err(|e| format!("Failed to deserialize exported data: {}", e))
}

#[wasm_bindgen]
pub fn convert_exported_data_to_pdf_wasm(
    exported_data_js: JsValue,
    offset_x: Option<f64>,
    offset_y: Option<f64>,
    width: Option<f64>,
    height: Option<f64>,
    background_color: Option<String>,
    scale: Option<f64>,
    font_map_js: JsValue,
) -> Vec<u8> {
    if let Some(w) = width {
        if !w.is_finite() || w <= 0.0 {
            let error_info = error_handling::WasmErrorInfo {
                error: format!("Invalid width: {}", w),
                error_type: "ValidationError".to_string(),
                details: format!("width must be a positive finite number, got {}", w),
                duc_data_length: 0,
                conversion_context: None,
            };
            return error_handling::error_to_wasm_bytes(&error_info);
        }
    }

    if let Some(h) = height {
        if !h.is_finite() || h <= 0.0 {
            let error_info = error_handling::WasmErrorInfo {
                error: format!("Invalid height: {}", h),
                error_type: "ValidationError".to_string(),
                details: format!("height must be a positive finite number, got {}", h),
                duc_data_length: 0,
                conversion_context: None,
            };
            return error_handling::error_to_wasm_bytes(&error_info);
        }
    }

    let exported_data = match deserialize_exported_data(exported_data_js) {
        Ok(data) => data,
        Err(details) => {
            let error_info = error_handling::WasmErrorInfo {
                error: details.clone(),
                error_type: "ValidationError".to_string(),
                details,
                duc_data_length: 0,
                conversion_context: None,
            };
            return error_handling::error_to_wasm_bytes(&error_info);
        }
    };

    let font_data = deserialize_font_map(font_map_js);
    let normalized_background = normalize_background_color(background_color);

    let mode = if offset_x.is_some() || offset_y.is_some() {
        ConversionMode::Crop {
            offset_x: offset_x.unwrap_or(0.0),
            offset_y: offset_y.unwrap_or(0.0),
            width,
            height,
        }
    } else {
        ConversionMode::Plot
    };

    let options = ConversionOptions {
        mode,
        scale,
        background_color: normalized_background,
        ..Default::default()
    };

    match convert_exported_data_to_pdf_with_fonts_and_options(exported_data, options, font_data) {
        Ok(pdf_bytes) => pdf_bytes,
        Err(e) => {
            error_handling::log_error_details(&e, 0, "Direct exported data conversion");
            let error_info = error_handling::create_error_info(&e, 0, None);
            error_handling::error_to_wasm_bytes(&error_info)
        }
    }
}

/// WASM binding for conversion with custom font data
/// font_map_js: a JS Map<string, Uint8Array> mapping font family names to TTF/OTF bytes
#[wasm_bindgen]
pub fn convert_duc_to_pdf_with_fonts_rs(duc_data: &[u8], font_map_js: JsValue) -> Vec<u8> {
    let font_data = deserialize_font_map(font_map_js);
    match convert_duc_to_pdf_with_fonts_and_options(
        duc_data,
        ConversionOptions::default(),
        font_data,
    ) {
        Ok(pdf_bytes) => pdf_bytes,
        Err(e) => {
            error_handling::log_error_details(
                &e,
                duc_data.len(),
                "Conversion with fonts (default options)",
            );
            let error_info = error_handling::create_error_info(&e, duc_data.len(), None);
            error_handling::error_to_wasm_bytes(&error_info)
        }
    }
}

/// WASM binding for standard conversion with fonts and an explicit manual drawing scale.
#[wasm_bindgen]
pub fn convert_duc_to_pdf_with_fonts_scaled_wasm(
    duc_data: &[u8],
    scale: f64,
    font_map_js: JsValue,
) -> Vec<u8> {
    let font_data = deserialize_font_map(font_map_js);
    let options = ConversionOptions {
        scale: Some(scale),
        ..Default::default()
    };

    match convert_duc_to_pdf_with_fonts_and_options(duc_data, options, font_data) {
        Ok(pdf_bytes) => pdf_bytes,
        Err(e) => {
            error_handling::log_error_details(
                &e,
                duc_data.len(),
                "Conversion with fonts and scale",
            );
            let options = ConversionOptions {
                scale: Some(scale),
                ..Default::default()
            };
            let error_info = error_handling::create_error_info(&e, duc_data.len(), Some(&options));
            error_handling::error_to_wasm_bytes(&error_info)
        }
    }
}

/// WASM binding for crop conversion with custom font data
#[wasm_bindgen]
pub fn convert_duc_to_pdf_crop_with_fonts_wasm(
    duc_data: &[u8],
    offset_x: f64,
    offset_y: f64,
    width: Option<f64>,
    height: Option<f64>,
    background_color: Option<String>,
    font_map_js: JsValue,
) -> Vec<u8> {
    if let Err(validation_error) = error_handling::validate_basic_inputs(
        duc_data,
        Some(offset_x),
        Some(offset_y),
        width,
        height,
    ) {
        let error_info = error_handling::WasmErrorInfo {
            error: validation_error.clone(),
            error_type: "ValidationError".to_string(),
            details: validation_error,
            duc_data_length: duc_data.len(),
            conversion_context: None,
        };
        return error_handling::error_to_wasm_bytes(&error_info);
    }

    let normalized_background = normalize_background_color(background_color);
    let font_data = deserialize_font_map(font_map_js);

    let options = ConversionOptions {
        mode: ConversionMode::Crop {
            offset_x,
            offset_y,
            width,
            height,
        },
        background_color: normalized_background.clone(),
        ..Default::default()
    };

    match convert_duc_to_pdf_with_fonts_and_options(duc_data, options, font_data) {
        Ok(pdf_bytes) => pdf_bytes,
        Err(e) => {
            error_handling::log_error_details(&e, duc_data.len(), "Crop conversion with fonts");
            error_handling::log_crop_details(offset_x, offset_y, width, height);
            let crop_options = ConversionOptions {
                mode: ConversionMode::Crop {
                    offset_x,
                    offset_y,
                    width,
                    height,
                },
                background_color: normalized_background,
                ..Default::default()
            };
            let error_info =
                error_handling::create_error_info(&e, duc_data.len(), Some(&crop_options));
            error_handling::error_to_wasm_bytes(&error_info)
        }
    }
}

/// WASM binding for crop conversion with fonts and explicit manual drawing scale.
#[wasm_bindgen]
pub fn convert_duc_to_pdf_crop_with_fonts_scaled_wasm(
    duc_data: &[u8],
    offset_x: f64,
    offset_y: f64,
    width: Option<f64>,
    height: Option<f64>,
    background_color: Option<String>,
    scale: f64,
    font_map_js: JsValue,
) -> Vec<u8> {
    if let Err(validation_error) = error_handling::validate_basic_inputs(
        duc_data,
        Some(offset_x),
        Some(offset_y),
        width,
        height,
    ) {
        let error_info = error_handling::WasmErrorInfo {
            error: validation_error.clone(),
            error_type: "ValidationError".to_string(),
            details: validation_error,
            duc_data_length: duc_data.len(),
            conversion_context: None,
        };
        return error_handling::error_to_wasm_bytes(&error_info);
    }

    let normalized_background = normalize_background_color(background_color);
    let font_data = deserialize_font_map(font_map_js);

    let options = ConversionOptions {
        mode: ConversionMode::Crop {
            offset_x,
            offset_y,
            width,
            height,
        },
        scale: Some(scale),
        background_color: normalized_background.clone(),
        ..Default::default()
    };

    match convert_duc_to_pdf_with_fonts_and_options(duc_data, options, font_data) {
        Ok(pdf_bytes) => pdf_bytes,
        Err(e) => {
            error_handling::log_error_details(
                &e,
                duc_data.len(),
                "Crop conversion with fonts and scale",
            );
            error_handling::log_crop_details(offset_x, offset_y, width, height);
            let crop_options = ConversionOptions {
                mode: ConversionMode::Crop {
                    offset_x,
                    offset_y,
                    width,
                    height,
                },
                scale: Some(scale),
                background_color: normalized_background,
                ..Default::default()
            };
            let error_info =
                error_handling::create_error_info(&e, duc_data.len(), Some(&crop_options));
            error_handling::error_to_wasm_bytes(&error_info)
        }
    }
}