docxide-pdf 0.16.3

Library and CLI for converting DOCX files to PDF, matching Microsoft Word's output as closely as possible
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
use std::collections::{HashMap, HashSet};
use std::io::Read;

use crate::geometry::{FormulaOp, PathFill};
use crate::model::{
    ArrowEnd, AutoFit, ConnectorShape, ConnectorType, CustomGeometry, CustomGuideDef,
    CustomPathCommand, CustomPathDef, HRelativeFrom, HorizontalPosition, Paragraph, ShapeFill,
    ShapeGeometry, TextAnchor, TextWarp, Textbox, VRelativeFrom, VerticalPosition, WrapType,
};

use super::images::{extent_dimensions, parse_anchor_position};
use super::color::{apply_color_transforms, parse_line_stroke, parse_solid_fill, resolve_dml_color};
use super::styles::{
    ThemeFillStyle, ThemeFonts,
};
use super::{
    DML_NS, MC_NS_TOP, ParseContext, VML_NS, WML_NS, WPD_NS, WPS_NS,
    dml as find_dml, dml_children as find_dml_all, wps as find_wps,
    emu_attr, parse_pt,
};

struct VmlBoxStyle {
    width: f32,
    height: f32,
    margin_left: f32,
    margin_top: f32,
    h_relative: HRelativeFrom,
    v_relative: VRelativeFrom,
}

/// Parse a VML shape `style` attribute (semicolon-separated `key:val`) into box
/// geometry: dimensions/margins in points and the position-relative anchors.
fn parse_vml_box_style(style_str: &str) -> VmlBoxStyle {
    let mut s = VmlBoxStyle {
        width: 0.0,
        height: 0.0,
        margin_left: 0.0,
        margin_top: 0.0,
        h_relative: HRelativeFrom::Column,
        v_relative: VRelativeFrom::Paragraph,
    };
    for part in style_str.split(';') {
        if let Some((key, val)) = part.trim().split_once(':') {
            let val = val.trim();
            match key.trim() {
                "width" => s.width = parse_pt(val).unwrap_or(0.0),
                "height" => s.height = parse_pt(val).unwrap_or(0.0),
                "margin-left" => s.margin_left = parse_pt(val).unwrap_or(0.0),
                "margin-top" => s.margin_top = parse_pt(val).unwrap_or(0.0),
                "mso-position-horizontal-relative" => {
                    s.h_relative = match val {
                        "page" => HRelativeFrom::Page,
                        "margin" => HRelativeFrom::Margin,
                        _ => HRelativeFrom::Column,
                    };
                }
                "mso-position-vertical-relative" => {
                    s.v_relative = match val {
                        "page" => VRelativeFrom::Page,
                        "margin" => VRelativeFrom::Margin,
                        _ => VRelativeFrom::Paragraph,
                    };
                }
                _ => {}
            }
        }
    }
    s
}

fn collect_dml_points(parent: roxmltree::Node) -> Vec<(String, String)> {
    find_dml_all(parent, "pt")
        .map(|pt| {
            (
                pt.attribute("x").unwrap_or("0").to_string(),
                pt.attribute("y").unwrap_or("0").to_string(),
            )
        })
        .collect()
}

pub(super) fn find_sp_pr<'a>(wsp: roxmltree::Node<'a, 'a>) -> Option<roxmltree::Node<'a, 'a>> {
    wsp.children().find(|n| {
        n.tag_name().name() == "spPr"
            && (n.tag_name().namespace() == Some(WPS_NS)
                || n.tag_name().namespace() == Some(DML_NS))
    })
}

fn find_wps_style_ref<'a>(
    wsp: roxmltree::Node<'a, 'a>,
    ref_name: &str,
) -> Option<roxmltree::Node<'a, 'a>> {
    let style = find_wps(wsp, "style")?;
    find_dml(style, ref_name)
}

pub(super) fn parse_txbx_content_paragraphs<R: Read + std::io::Seek>(
    txbx_content: roxmltree::Node,
    ctx: &mut ParseContext<'_, R>,
) -> Vec<Paragraph> {
    let mut paragraphs = Vec::new();
    let mut counters: HashMap<(u32, u8), u32> = HashMap::new();
    let mut last_seen_level: HashMap<u32, u8> = HashMap::new();
    let mut applied_overrides: HashSet<(u32, u8)> = HashSet::new();
    let opts = super::paragraph::ParagraphOptions::default();
    for p in txbx_content
        .children()
        .filter(|n| n.tag_name().name() == "p" && n.tag_name().namespace() == Some(WML_NS))
    {
        paragraphs.push(super::paragraph::build_paragraph(
            p, ctx, &mut counters, &mut last_seen_level, &mut applied_overrides, &opts,
        ));
    }
    paragraphs
}

fn parse_gradient_fill(sp_pr: roxmltree::Node, theme: &ThemeFonts) -> Option<ShapeFill> {
    let grad_fill = find_dml(sp_pr, "gradFill")?;
    let gs_lst = find_dml(grad_fill, "gsLst")?;

    let stops: Vec<([u8; 3], f32)> = find_dml_all(gs_lst, "gs")
        .filter_map(|gs| {
            let pos = gs
                .attribute("pos")
                .and_then(|v| v.parse::<f32>().ok())
                .map(|v| v / 100_000.0)
                .unwrap_or(0.0);
            resolve_dml_color(gs, theme).map(|color| (color, pos))
        })
        .collect();
    if stops.is_empty() {
        return None;
    }

    // OOXML a:lin @ang is in 60,000ths of a degree
    let angle_deg = find_dml(grad_fill, "lin")
        .and_then(|lin| lin.attribute("ang"))
        .and_then(|v| v.parse::<f32>().ok())
        .map(|v| v / 60_000.0)
        .unwrap_or(0.0);

    Some(ShapeFill::LinearGradient { stops, angle_deg })
}

fn parse_style_fill(wsp: roxmltree::Node, theme: &ThemeFonts) -> Option<ShapeFill> {
    let fill_ref = find_wps_style_ref(wsp, "fillRef")?;

    let idx = fill_ref
        .attribute("idx")
        .and_then(|v| v.parse::<u32>().ok())
        .unwrap_or(0);
    if idx == 0 {
        return None;
    }

    let base_color = resolve_dml_color(fill_ref, theme)?;

    let fill_style_idx = (idx as usize).saturating_sub(1);
    match theme.fill_styles.get(fill_style_idx) {
        Some(ThemeFillStyle::Gradient { stops, angle_deg }) if !stops.is_empty() => {
            let resolved_stops: Vec<([u8; 3], f32)> = stops
                .iter()
                .map(|stop| {
                    let color = apply_color_transforms(base_color, &stop.transforms);
                    (color, stop.position)
                })
                .collect();
            Some(ShapeFill::LinearGradient {
                stops: resolved_stops,
                angle_deg: *angle_deg,
            })
        }
        _ => Some(ShapeFill::Solid(base_color)),
    }
}

/// Parse `a:prstGeom` or `a:custGeom` from an spPr node into `ShapeGeometry`.
pub(super) fn parse_shape_geometry(sp_pr: roxmltree::Node) -> ShapeGeometry {
    if let Some(prst_geom) = find_dml(sp_pr, "prstGeom") {
        let preset = prst_geom.attribute("prst").unwrap_or("rect").to_string();
        let adjustments = parse_avlst(prst_geom);
        return ShapeGeometry {
            preset: Some(preset),
            adjustments,
            custom: None,
        };
    }

    if let Some(cust_geom) = find_dml(sp_pr, "custGeom") {
        if let Some(custom) = parse_custom_geometry(cust_geom) {
            return ShapeGeometry {
                preset: None,
                adjustments: Vec::new(),
                custom: Some(custom),
            };
        }
    }

    ShapeGeometry::default()
}

pub(super) fn parse_avlst(parent: roxmltree::Node) -> Vec<(String, i64)> {
    let Some(avlst) = find_dml(parent, "avLst") else {
        return Vec::new();
    };
    find_dml_all(avlst, "gd")
        .filter_map(|gd| {
            let name = gd.attribute("name")?.to_string();
            let fmla = gd.attribute("fmla")?;
            let val = fmla.strip_prefix("val ")?.trim().parse::<i64>().ok()?;
            Some((name, val))
        })
        .collect()
}

fn parse_custom_geometry(cust_geom: roxmltree::Node) -> Option<CustomGeometry> {
    let adjust_defaults = parse_avlst(cust_geom);

    let guides = find_dml(cust_geom, "gdLst")
        .map(|gdlst| {
            find_dml_all(gdlst, "gd")
                .filter_map(|gd| {
                    let name = gd.attribute("name")?.to_string();
                    let fmla = gd.attribute("fmla")?;
                    let parts: Vec<&str> = fmla.split_whitespace().collect();
                    let op = FormulaOp::from_str(parts.first()?)?;
                    let x = parts.get(1).unwrap_or(&"").to_string();
                    let y = parts.get(2).unwrap_or(&"").to_string();
                    let z = parts.get(3).unwrap_or(&"").to_string();
                    Some(CustomGuideDef { name, op, x, y, z })
                })
                .collect()
        })
        .unwrap_or_default();

    let paths = find_dml(cust_geom, "pathLst")
        .map(|path_lst| {
            find_dml_all(path_lst, "path")
                .map(|path| {
                    let w = path.attribute("w").and_then(|v| v.parse::<i64>().ok());
                    let h = path.attribute("h").and_then(|v| v.parse::<i64>().ok());
                    let fill = match path.attribute("fill") {
                        Some("none") => PathFill::None,
                        _ => PathFill::Norm,
                    };
                    let stroke = path.attribute("stroke") != Some("0");
                    let commands = parse_path_commands(path);
                    CustomPathDef {
                        commands,
                        w,
                        h,
                        fill,
                        stroke,
                    }
                })
                .collect()
        })
        .unwrap_or_default();

    Some(CustomGeometry {
        adjust_defaults,
        guides,
        paths,
    })
}

fn parse_path_commands(path: roxmltree::Node) -> Vec<CustomPathCommand> {
    let mut commands = Vec::new();
    for child in path
        .children()
        .filter(|n| n.tag_name().namespace() == Some(DML_NS))
    {
        match child.tag_name().name() {
            "moveTo" => {
                if let Some((x, y)) = dml_pt(child) {
                    commands.push(CustomPathCommand::MoveTo { x, y });
                }
            }
            "lnTo" => {
                if let Some((x, y)) = dml_pt(child) {
                    commands.push(CustomPathCommand::LineTo { x, y });
                }
            }
            "arcTo" => {
                commands.push(CustomPathCommand::ArcTo {
                    wr: child.attribute("wR").unwrap_or("0").to_string(),
                    hr: child.attribute("hR").unwrap_or("0").to_string(),
                    st_ang: child.attribute("stAng").unwrap_or("0").to_string(),
                    sw_ang: child.attribute("swAng").unwrap_or("0").to_string(),
                });
            }
            "cubicBezTo" => {
                let pts = collect_dml_points(child);
                if pts.len() == 3 {
                    commands.push(CustomPathCommand::CubicBezTo {
                        x1: pts[0].0.clone(),
                        y1: pts[0].1.clone(),
                        x2: pts[1].0.clone(),
                        y2: pts[1].1.clone(),
                        x3: pts[2].0.clone(),
                        y3: pts[2].1.clone(),
                    });
                }
            }
            "quadBezTo" => {
                let pts = collect_dml_points(child);
                if pts.len() == 2 {
                    commands.push(CustomPathCommand::QuadBezTo {
                        x1: pts[0].0.clone(),
                        y1: pts[0].1.clone(),
                        x2: pts[1].0.clone(),
                        y2: pts[1].1.clone(),
                    });
                }
            }
            "close" => {
                commands.push(CustomPathCommand::Close);
            }
            _ => {}
        }
    }
    commands
}

fn dml_pt(parent: roxmltree::Node) -> Option<(String, String)> {
    let pt = find_dml(parent, "pt")?;
    Some((
        pt.attribute("x").unwrap_or("0").to_string(),
        pt.attribute("y").unwrap_or("0").to_string(),
    ))
}

fn parse_body_margins(wsp: roxmltree::Node) -> (f32, f32, f32, f32) {
    let Some(bp) = find_wps(wsp, "bodyPr") else {
        return (3.6, 7.2, 3.6, 7.2); // Word defaults: 0.05" top/bottom, 0.1" left/right
    };
    let emu_to_pt = |attr: &str, default: f32| -> f32 {
        bp.attribute(attr)
            .and_then(|v| v.parse::<f32>().ok())
            .map(super::emu_to_pts)
            .unwrap_or(default)
    };
    (
        emu_to_pt("tIns", 3.6),
        emu_to_pt("lIns", 7.2),
        emu_to_pt("bIns", 3.6),
        emu_to_pt("rIns", 7.2),
    )
}

/// WordArt defaults to 0 margins unless explicitly set.
fn parse_wordart_body_margins(wsp: roxmltree::Node) -> (f32, f32, f32, f32) {
    let Some(bp) = find_wps(wsp, "bodyPr") else {
        return (0.0, 0.0, 0.0, 0.0);
    };
    (
        emu_attr(bp, "tIns"),
        emu_attr(bp, "lIns"),
        emu_attr(bp, "bIns"),
        emu_attr(bp, "rIns"),
    )
}

pub(super) struct WspResult {
    pub(super) paragraphs: Vec<Paragraph>,
    pub(super) fill: Option<ShapeFill>,
    pub(super) shape_type: ShapeGeometry,
    pub(super) stroke_color: Option<[u8; 3]>,
    pub(super) stroke_width: f32,
    pub(super) text_anchor: TextAnchor,
    pub(super) margin_top: f32,
    pub(super) margin_left: f32,
    pub(super) margin_bottom: f32,
    pub(super) margin_right: f32,
    pub(super) no_text_wrap: bool,
    pub(super) is_wordart: bool,
    pub(super) text_warp: Option<TextWarp>,
    pub(super) auto_fit: AutoFit,
}

pub(super) fn parse_textbox_from_wsp<R: Read + std::io::Seek>(
    anchor: roxmltree::Node,
    ctx: &mut ParseContext<'_, R>,
) -> Option<WspResult> {
    let wsp = anchor
        .descendants()
        .find(|n| n.tag_name().name() == "wsp" && n.tag_name().namespace() == Some(WPS_NS))?;
    parse_wsp_shape(wsp, ctx)
}

/// Parse a single `wps:wsp` node into a shape result. Used both for the
/// single-shape drawing path and for children of canvases/groups.
pub(super) fn parse_wsp_shape<R: Read + std::io::Seek>(
    wsp: roxmltree::Node,
    ctx: &mut ParseContext<'_, R>,
) -> Option<WspResult> {
    let sp_pr = find_sp_pr(wsp);

    // Line/arc presets without text are connectors — decline so the caller
    // falls through to the connector parser, which renders flipH/flipV and
    // arc sweep angles that the preset-geometry textbox path doesn't.
    let prst = sp_pr
        .and_then(|sp| find_dml(sp, "prstGeom"))
        .and_then(|g| g.attribute("prst"));
    if matches!(prst, Some("line" | "straightConnector1" | "arc")) && find_wps(wsp, "txbx").is_none()
    {
        return None;
    }
    let has_no_fill = sp_pr.is_some_and(|sp| find_dml(sp, "noFill").is_some());
    // Explicit a:noFill overrides any style-ref (fillRef) fill
    let fill: Option<ShapeFill> = if has_no_fill {
        None
    } else {
        sp_pr
            .and_then(|sp| {
                parse_solid_fill(sp, ctx.theme)
                    .map(ShapeFill::Solid)
                    .or_else(|| parse_gradient_fill(sp, ctx.theme))
            })
            .or_else(|| parse_style_fill(wsp, ctx.theme))
    };

    let ln_node = sp_pr.and_then(|sp| find_dml(sp, "ln"));
    let ln_no_fill = ln_node.is_some_and(|ln| find_dml(ln, "noFill").is_some());
    let explicit_ln_width = ln_node
        .and_then(|ln| ln.attribute("w"))
        .and_then(|v| v.parse::<f32>().ok())
        .map(super::emu_to_pts);
    let (stroke_color, stroke_width) = if ln_no_fill {
        (None, 0.0)
    } else if let Some((color, width)) = ln_node.and_then(|ln| parse_line_stroke(ln, ctx.theme)) {
        (Some(color), width)
    } else if let Some(color) = parse_style_stroke(wsp, ctx.theme) {
        // No explicit line color: fall back to the shape style's lnRef stroke
        (
            Some(color),
            explicit_ln_width.unwrap_or_else(|| parse_style_stroke_width(wsp)),
        )
    } else {
        (None, 0.0)
    };

    let shape_type = sp_pr.map(parse_shape_geometry).unwrap_or_default();

    let (mut margin_top, mut margin_left, mut margin_bottom, mut margin_right) =
        parse_body_margins(wsp);

    let body_pr = find_wps(wsp, "bodyPr");
    let no_text_wrap = body_pr
        .and_then(|bp| bp.attribute("wrap"))
        .is_some_and(|w| w == "none");

    let text_anchor = match body_pr.and_then(|bp| bp.attribute("anchor")) {
        Some("ctr") => TextAnchor::Middle,
        Some("b") => TextAnchor::Bottom,
        _ => TextAnchor::Top,
    };

    let wa_props = body_pr
        .map(super::wordart::parse_wordart_body_pr)
        .unwrap_or(super::wordart::WordArtBodyProps {
            is_wordart: false,
            text_warp: None,
            auto_fit: AutoFit::None,
        });

    // WordArt defaults to zero body margins unless explicitly set
    if wa_props.is_wordart {
        let (wt, wl, wb, wr) = parse_wordart_body_margins(wsp);
        margin_top = wt;
        margin_left = wl;
        margin_bottom = wb;
        margin_right = wr;
    }

    let paragraphs = find_wps(wsp, "txbx")
        .and_then(|txbx| {
            txbx.children().find(|n| {
                n.tag_name().name() == "txbxContent" && n.tag_name().namespace() == Some(WML_NS)
            })
        })
        .map(|tc| parse_txbx_content_paragraphs(tc, ctx))
        .unwrap_or_default();

    if paragraphs.is_empty() && (has_no_fill || fill.is_none()) && stroke_color.is_none() {
        return None;
    }

    Some(WspResult {
        paragraphs,
        fill,
        shape_type,
        stroke_color,
        stroke_width,
        text_anchor,
        margin_top,
        margin_left,
        margin_bottom,
        margin_right,
        no_text_wrap,
        is_wordart: wa_props.is_wordart,
        text_warp: wa_props.text_warp,
        auto_fit: wa_props.auto_fit,
    })
}

pub(super) fn parse_connector_from_wsp(
    anchor: roxmltree::Node,
    theme: &ThemeFonts,
) -> Option<ConnectorShape> {
    let wsp = anchor
        .descendants()
        .find(|n| n.tag_name().name() == "wsp" && n.tag_name().namespace() == Some(WPS_NS))?;

    let (h_position, _, v_pos, _) = parse_anchor_position(anchor);
    let (display_w, display_h) = extent_dimensions(anchor);
    let v_offset = match v_pos {
        VerticalPosition::Offset(o) => o,
        _ => 0.0,
    };
    let x = match h_position {
        HorizontalPosition::Offset(v) => v,
        _ => 0.0,
    };

    let mut conn = parse_connector_shape_node(wsp, theme)?;
    conn.x = x;
    conn.y = v_offset;
    conn.width = display_w;
    conn.height = display_h;
    conn.z_index = anchor
        .attribute("relativeHeight")
        .and_then(|v| v.parse::<u32>().ok())
        .unwrap_or(0);
    Some(conn)
}

/// Parse a `wps:wsp` connector node (line/arc preset) into a ConnectorShape
/// with zeroed position/size — the caller supplies the placement.
pub(super) fn parse_connector_shape_node(
    wsp: roxmltree::Node,
    theme: &ThemeFonts,
) -> Option<ConnectorShape> {
    let sp_pr = find_sp_pr(wsp)?;
    let prst_geom = find_dml(sp_pr, "prstGeom")?;
    let prst = prst_geom.attribute("prst")?;

    let xfrm = find_dml(sp_pr, "xfrm");

    let connector_type = match prst {
        "line" | "straightConnector1" => {
            let flip_h = xfrm
                .and_then(|x| x.attribute("flipH"))
                .is_some_and(|v| v == "1");
            let flip_v = xfrm
                .and_then(|x| x.attribute("flipV"))
                .is_some_and(|v| v == "1");
            ConnectorType::Line { flip_h, flip_v }
        }
        "arc" => {
            let rotation = xfrm
                .and_then(|x| x.attribute("rot"))
                .and_then(|v| v.parse::<f32>().ok())
                .unwrap_or(0.0)
                / 60000.0;

            let mut adj1 = 0.0_f32;
            let mut adj2 = 0.0_f32;
            for gd in prst_geom
                .descendants()
                .filter(|n| n.tag_name().name() == "gd" && n.tag_name().namespace() == Some(DML_NS))
            {
                let name = gd.attribute("name").unwrap_or("");
                let val = gd
                    .attribute("fmla")
                    .and_then(|f| f.strip_prefix("val "))
                    .and_then(|v| v.parse::<f32>().ok())
                    .unwrap_or(0.0)
                    / 60000.0;
                match name {
                    "adj1" => adj1 = val,
                    "adj2" => adj2 = val,
                    _ => {}
                }
            }
            ConnectorType::Arc {
                start_angle: adj1,
                end_angle: adj2,
                rotation,
            }
        }
        _ => return None,
    };

    let ln_node = find_dml(sp_pr, "ln");
    // Explicit a:ln formatting overrides the style matrix lnRef (OOXML precedence).
    // The 50cm connector sets a:ln/solidFill=tx1 (black) but lnRef=accent1 (blue);
    // Word draws it black, so the direct fill must win over the style ref.
    let stroke_color = ln_node
        .and_then(|ln| parse_solid_fill(ln, theme))
        .or_else(|| parse_style_stroke(wsp, theme))
        .unwrap_or([0, 0, 0]);
    let stroke_width = ln_node
        .and_then(|ln| ln.attribute("w"))
        .and_then(|v| v.parse::<f32>().ok())
        .map(super::emu_to_pts)
        .unwrap_or_else(|| parse_style_stroke_width(wsp));

    let (head_end, tail_end) = ln_node
        .map(|ln| {
            let head = find_dml(ln, "headEnd")
                .and_then(|n| n.attribute("type"))
                .map(ArrowEnd::from_attr)
                .unwrap_or_default();
            let tail = find_dml(ln, "tailEnd")
                .and_then(|n| n.attribute("type"))
                .map(ArrowEnd::from_attr)
                .unwrap_or_default();
            (head, tail)
        })
        .unwrap_or_default();

    Some(ConnectorShape {
        x: 0.0,
        y: 0.0,
        width: 0.0,
        height: 0.0,
        stroke_color,
        stroke_width,
        connector_type,
        head_end,
        tail_end,
        z_index: 0,
    })
}

fn parse_style_stroke(wsp: roxmltree::Node, theme: &ThemeFonts) -> Option<[u8; 3]> {
    let ln_ref = find_wps_style_ref(wsp, "lnRef")?;
    let idx = ln_ref
        .attribute("idx")
        .and_then(|v| v.parse::<u32>().ok())
        .unwrap_or(0);
    if idx == 0 {
        return None;
    }
    resolve_dml_color(ln_ref, theme)
}

fn parse_style_stroke_width(wsp: roxmltree::Node) -> f32 {
    let idx = find_wps_style_ref(wsp, "lnRef")
        .and_then(|lr| lr.attribute("idx"))
        .and_then(|v| v.parse::<u32>().ok())
        .unwrap_or(0);
    match idx {
        0 => 0.0,
        1 => 0.75,
        2 => 1.5,
        3 => 2.25,
        _ => 1.0,
    }
}

/// Parse a VML color value: `#RRGGBB`, a named color, or a theme token like
/// `white [3212]` (the `[idx]` suffix is the resolved theme color we ignore in
/// favor of the spelled-out name). Returns None for unrecognized values so the
/// caller can fall back to a default.
fn parse_vml_color(val: &str) -> Option<[u8; 3]> {
    let val = val.trim().split('[').next().unwrap_or("").trim();
    if let Some(hex) = val.strip_prefix('#') {
        if hex.len() == 6 {
            return super::parse_hex_color(hex);
        }
        if hex.len() == 3 {
            let expand = |c: &str| u8::from_str_radix(&c.repeat(2), 16).ok();
            return Some([
                expand(&hex[0..1])?,
                expand(&hex[1..2])?,
                expand(&hex[2..3])?,
            ]);
        }
        return None;
    }
    match val.to_ascii_lowercase().as_str() {
        "black" => Some([0, 0, 0]),
        "white" => Some([255, 255, 255]),
        "red" => Some([255, 0, 0]),
        "green" => Some([0, 128, 0]),
        "blue" => Some([0, 0, 255]),
        "yellow" => Some([255, 255, 0]),
        "gray" | "grey" => Some([128, 128, 128]),
        "silver" => Some([192, 192, 192]),
        _ => None,
    }
}

/// Map a VML shape type code (`o:spt`, also encoded as the `t<N>` suffix of a
/// shapetype id like `#_x0000_t87`) to a DrawingML preset geometry name for the
/// stroke-only shapes we can render. Only the brace/bracket family is mapped —
/// these are the common stroke-only VML presets that carry no textbox.
fn vml_spt_to_preset(spt: u32) -> Option<&'static str> {
    match spt {
        85 => Some("leftBracket"),
        86 => Some("rightBracket"),
        87 => Some("leftBrace"),
        88 => Some("rightBrace"),
        _ => None,
    }
}

/// Resolve a VML shape's preset geometry from its `o:spt` attribute or its
/// `type="#_x0000_t<N>"` reference.
fn vml_shape_preset(shape: roxmltree::Node) -> Option<&'static str> {
    const OFFICE_NS: &str = "urn:schemas-microsoft-com:office:office";
    let spt = shape
        .attribute((OFFICE_NS, "spt"))
        .and_then(|v| v.trim().parse::<f64>().ok().map(|f| f as u32))
        .or_else(|| {
            shape
                .attribute("type")
                .and_then(|t| t.rsplit_once('t'))
                .and_then(|(_, n)| n.parse::<u32>().ok())
        })?;
    vml_spt_to_preset(spt)
}

/// Build a paragraph-less stroked textbox for a VML preset shape that has no
/// textbox/textpath (e.g. a curly brace). Returns None for unrecognized presets
/// so such shapes remain dropped rather than rendered as a stray rectangle.
fn parse_vml_geometry_shape(shape: roxmltree::Node) -> Option<Textbox> {
    let preset = vml_shape_preset(shape)?;

    let stroked = !matches!(shape.attribute("stroked"), Some("f") | Some("false"));
    if !stroked {
        return None;
    }
    let stroke_width = shape
        .attribute("strokeweight")
        .and_then(parse_pt)
        .filter(|w| *w > 0.0)
        .unwrap_or(0.75);
    let stroke_color = shape
        .attribute("strokecolor")
        .and_then(parse_vml_color)
        .unwrap_or([0, 0, 0]);

    let style_str = shape.attribute("style").unwrap_or("");
    let VmlBoxStyle {
        width,
        height,
        margin_left,
        margin_top,
        h_relative,
        v_relative,
    } = parse_vml_box_style(style_str);
    if width <= 0.0 || height <= 0.0 {
        return None;
    }

    Some(Textbox {
        paragraphs: Vec::new(),
        width_pt: width,
        height_pt: height,
        h_position: HorizontalPosition::Offset(margin_left),
        h_relative_from: h_relative,
        v_offset_pt: margin_top,
        v_position: VerticalPosition::Offset(margin_top),
        v_relative_from: v_relative,
        fill: None,
        shape_type: ShapeGeometry {
            preset: Some(preset.to_string()),
            adjustments: Vec::new(),
            custom: None,
        },
        stroke_color: Some(stroke_color),
        stroke_width,
        text_anchor: TextAnchor::Top,
        margin_left: 0.0,
        margin_right: 0.0,
        margin_top: 0.0,
        margin_bottom: 0.0,
        wrap_type: WrapType::None,
        dist_top: 0.0,
        dist_bottom: 0.0,
        behind_doc: false,
        no_text_wrap: true,
        is_wordart: false,
        text_warp: None,
        auto_fit: AutoFit::None,
        z_index: 0,
        indent_relative: false,
    })
}

pub(super) fn parse_textbox_from_vml<R: Read + std::io::Seek>(
    pict_node: roxmltree::Node,
    ctx: &mut ParseContext<'_, R>,
) -> Option<Textbox> {
    let shape = pict_node.children().find(|n| {
        n.tag_name().namespace() == Some(VML_NS) && matches!(n.tag_name().name(), "shape" | "rect")
    })?;

    // VML WordArt uses v:textpath instead of v:textbox
    let Some(textbox_node) = shape
        .children()
        .find(|n| n.tag_name().name() == "textbox" && n.tag_name().namespace() == Some(VML_NS))
    else {
        if let Some(tp) = shape.children().find(|n| {
            n.tag_name().name() == "textpath" && n.tag_name().namespace() == Some(VML_NS)
        }) {
            return super::wordart::parse_vml_wordart(shape, tp, ctx.styles, ctx.theme);
        }
        // Stroke-only VML preset shapes (e.g. a curly brace, o:spt 87) have
        // neither a textbox nor a textpath. They were previously dropped
        // entirely (annotation #174 — the blue "{" wrapping the paragraphs).
        // Build a paragraph-less stroked shape from the preset geometry.
        return parse_vml_geometry_shape(shape);
    };
    let txbx_content = textbox_node.children().find(|n| {
        n.tag_name().name() == "txbxContent" && n.tag_name().namespace() == Some(WML_NS)
    })?;

    let style_str = shape.attribute("style").unwrap_or("");
    let VmlBoxStyle {
        width,
        height,
        margin_left,
        margin_top,
        h_relative,
        v_relative,
    } = parse_vml_box_style(style_str);

    // VML shapes are stroked by default (black, 0.75pt) unless stroked="f".
    // Word renders this border, so honor it — previously every VML textbox was
    // forced borderless, dropping e.g. the "Nota Bene" box outline.
    let stroked = !matches!(shape.attribute("stroked"), Some("f") | Some("false"));
    let (stroke_color, stroke_width) = if stroked {
        let w = shape
            .attribute("strokeweight")
            .and_then(parse_pt)
            .filter(|w| *w > 0.0)
            .unwrap_or(0.75);
        let c = shape
            .attribute("strokecolor")
            .and_then(parse_vml_color)
            .unwrap_or([0, 0, 0]);
        (Some(c), w)
    } else {
        (None, 0.0)
    };

    let paragraphs =
        parse_txbx_content_paragraphs(txbx_content, ctx);
    if paragraphs.is_empty() {
        return None;
    }
    Some(Textbox {
        paragraphs,
        width_pt: width,
        height_pt: height,
        h_position: HorizontalPosition::Offset(margin_left),
        h_relative_from: h_relative,
        v_offset_pt: margin_top,
        v_position: VerticalPosition::Offset(margin_top),
        v_relative_from: v_relative,
        fill: None,
        shape_type: ShapeGeometry::default(),
        stroke_color,
        stroke_width,
        text_anchor: TextAnchor::Top,
        margin_left: 7.2,
        margin_right: 7.2,
        margin_top: 3.6,
        margin_bottom: 3.6,
        wrap_type: WrapType::None,
        dist_top: 0.0,
        dist_bottom: 0.0,
        behind_doc: false,
        no_text_wrap: false,
        is_wordart: false,
        text_warp: None,
        auto_fit: AutoFit::None,
        z_index: 0,
        indent_relative: false,
    })
}

pub(super) fn collect_textboxes_from_paragraph<R: Read + std::io::Seek>(
    para_node: roxmltree::Node,
    ctx: &mut ParseContext<'_, R>,
) -> Vec<Textbox> {
    let mut textboxes = Vec::new();

    for child in para_node.children() {
        let ns = child.tag_name().namespace();
        let name = child.tag_name().name();
        if ns == Some(MC_NS_TOP) && name == "AlternateContent" {
            let choice = child.children().find(|n| {
                n.tag_name().namespace() == Some(MC_NS_TOP) && n.tag_name().name() == "Choice"
            });
            let fallback = child.children().find(|n| {
                n.tag_name().namespace() == Some(MC_NS_TOP) && n.tag_name().name() == "Fallback"
            });

            if let Some(branch) = choice {
                for drawing in branch.children().filter(|n| {
                    n.tag_name().namespace() == Some(WML_NS) && n.tag_name().name() == "drawing"
                }) {
                    for container in drawing.children().filter(|n| {
                        n.tag_name().namespace() == Some(WPD_NS) && n.tag_name().name() == "anchor"
                    }) {
                        let (display_w, display_h) = extent_dimensions(container);

                        if let Some(wsp) =
                            parse_textbox_from_wsp(container, ctx)
                        {
                            let (h_position, h_relative, v_pos, v_relative) =
                                parse_anchor_position(container);
                            let v_offset = match v_pos {
                                VerticalPosition::Offset(o) => o,
                                _ => 0.0,
                            };
                            let (wrap_type, _, _) = super::images::parse_wrap_type(container);
                            let behind_doc = container.attribute("behindDoc") == Some("1");
                            let dist_top = emu_attr(container, "distT");
                            let dist_bottom = emu_attr(container, "distB");
                            textboxes.push(Textbox {
                                paragraphs: wsp.paragraphs,
                                width_pt: display_w,
                                height_pt: display_h,
                                h_position,
                                h_relative_from: h_relative,
                                v_offset_pt: v_offset,
                                v_position: v_pos,
                                v_relative_from: v_relative,
                                fill: wsp.fill,
                                shape_type: wsp.shape_type,
                                stroke_color: wsp.stroke_color,
                                stroke_width: wsp.stroke_width,
                                text_anchor: wsp.text_anchor,
                                margin_left: wsp.margin_left,
                                margin_right: wsp.margin_right,
                                margin_top: wsp.margin_top,
                                margin_bottom: wsp.margin_bottom,
                                wrap_type,
                                dist_top,
                                dist_bottom,
                                behind_doc,
                                no_text_wrap: wsp.no_text_wrap,
                                is_wordart: wsp.is_wordart,
                                text_warp: wsp.text_warp,
                                auto_fit: wsp.auto_fit,
                                z_index: container
                                    .attribute("relativeHeight")
                                    .and_then(|v| v.parse::<u32>().ok())
                                    .unwrap_or(0),
                                indent_relative: false,
                            });
                        }
                    }
                }
            } else if let Some(branch) = fallback {
                for pict in branch.children().filter(|n| {
                    n.tag_name().namespace() == Some(WML_NS) && n.tag_name().name() == "pict"
                }) {
                    if let Some(tb) =
                        parse_textbox_from_vml(pict, ctx)
                    {
                        textboxes.push(tb);
                    }
                }
                for r in branch.children().filter(|n| {
                    n.tag_name().namespace() == Some(WML_NS) && n.tag_name().name() == "r"
                }) {
                    for pict in r.children().filter(|n| {
                        n.tag_name().namespace() == Some(WML_NS) && n.tag_name().name() == "pict"
                    }) {
                        if let Some(tb) =
                            parse_textbox_from_vml(pict, ctx)
                        {
                            textboxes.push(tb);
                        }
                    }
                }
            }
        }
    }
    textboxes
}