easydoc 0.1.0

A Rust library for easy DOC/DOCX document operations — read, write, template fill, Markdown conversion, and streaming event processing
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
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
//! Integration tests for the easydoc writer — produces real DOCX files.

use easydoc::ConverterRegistry;
use easydoc::DocumentMeta;
use easydoc::prelude::*;
use easydoc::{CollectListener, DocError, DocReadContext, DocReadListener};
use easydoc::{
    DocImage, DocWriteContext, DocWriteHandler, FillConfig, FillDirection, ParagraphContext,
    TableWriteContext,
};
use std::fs;
use tempfile::TempDir;

/// A simple test struct for table writing.
#[derive(Debug, Clone)]
struct TestUser {
    name: String,
    age: u32,
    email: String,
}

// Manual DocxRow impl for testing (derive will be used in production)
impl DocxRow for TestUser {
    fn schema() -> &'static [TableColumn] {
        static SCHEMA: std::sync::LazyLock<Vec<TableColumn>> = std::sync::LazyLock::new(|| {
            vec![
                TableColumn::new("Name", "name", 0).order(0).width("30%"),
                TableColumn::new("Age", "age", 1).order(1).width("15%"),
                TableColumn::new("Email", "email", 2).order(2).width("55%"),
            ]
        });
        &SCHEMA
    }

    fn from_row(row: &RowData) -> Result<Self> {
        Ok(TestUser {
            name: match &row.cells.first() {
                Some(cell) => match &cell.value {
                    DocValue::String(s) => s.clone(),
                    other => format!("{other:?}"),
                },
                None => String::new(),
            },
            age: match row.cells.get(1) {
                Some(cell) => match &cell.value {
                    DocValue::String(s) => s.parse().unwrap_or(0),
                    DocValue::Int(n) => *n as u32,
                    _ => 0,
                },
                None => 0,
            },
            email: match row.cells.get(2) {
                Some(cell) => match &cell.value {
                    DocValue::String(s) => s.clone(),
                    other => format!("{other:?}"),
                },
                None => String::new(),
            },
        })
    }

    fn from_row_with_converters(_row: &RowData, _registry: &ConverterRegistry) -> Result<Self> {
        unimplemented!("read not needed for write test")
    }

    fn to_row(&self) -> Result<Vec<CellData>> {
        Ok(vec![
            CellData::new(self.name.clone()),
            CellData::new(self.age.to_string()),
            CellData::new(self.email.clone()),
        ])
    }

    fn to_row_with_converters(&self, _registry: &ConverterRegistry) -> Result<Vec<CellData>> {
        self.to_row()
    }
}

#[test]
fn test_write_simple_table() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("test_users.docx");

    let users = vec![
        TestUser {
            name: "Alice".into(),
            age: 30,
            email: "alice@example.com".into(),
        },
        TestUser {
            name: "Bob".into(),
            age: 25,
            email: "bob@example.com".into(),
        },
    ];

    EasyDoc::write_table(&path, &users)
        .title("User Report")
        .do_write()
        .expect("write should succeed");

    assert!(path.exists(), "output file should exist");
    let size = fs::metadata(&path).unwrap().len();
    assert!(size > 0, "file should not be empty");

    // Verify it's a valid ZIP (DOCX is a ZIP)
    let file = fs::File::open(&path).unwrap();
    let mut archive = zip::ZipArchive::new(file).expect("should be valid ZIP");
    assert!(
        archive.by_name("word/document.xml").is_ok(),
        "should contain document.xml"
    );
}

#[test]
fn test_write_document() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("test_doc.docx");

    EasyDoc::document(&path)
        .title("Test Doc")
        .author("Test Author")
        .add_heading("Section 1", HeadingLevel::H1)
        .add_paragraph(
            Paragraph::new()
                .add_text("Hello ")
                .add_run(Run::new("World").bold().size(28)),
        )
        .add_paragraph(Paragraph::new().add_text("Second paragraph."))
        .save()
        .expect("save should succeed");

    assert!(path.exists());
    let size = fs::metadata(&path).unwrap().len();
    assert!(size > 0, "document should not be empty");

    // Verify ZIP structure
    let file = fs::File::open(&path).unwrap();
    let mut archive = zip::ZipArchive::new(file).expect("should be valid ZIP");
    assert!(archive.by_name("word/document.xml").is_ok());
}

#[test]
fn test_round_trip_write_and_read_text() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("roundtrip.docx");

    // Write a document
    EasyDoc::document(&path)
        .add_paragraph(Paragraph::new().add_text("Hello, round-trip test!"))
        .add_paragraph(Paragraph::new().add_text("Second paragraph here."))
        .save()
        .expect("write should succeed");

    // Read it back
    let text = EasyDoc::read_text(&path).expect("read should succeed");
    assert!(
        text.contains("round-trip test"),
        "text should contain written content: {text}"
    );
    assert!(
        text.contains("Second paragraph"),
        "text should contain second paragraph: {text}"
    );
}

#[test]
fn test_round_trip_write_and_read_table() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("roundtrip_table.docx");

    let users = vec![
        TestUser {
            name: "Alice".into(),
            age: 30,
            email: "alice@e.com".into(),
        },
        TestUser {
            name: "Bob".into(),
            age: 25,
            email: "bob@e.com".into(),
        },
    ];

    // Write table
    EasyDoc::write_table(&path, &users)
        .title("Users")
        .do_write()
        .expect("write should succeed");

    // Read tables back
    let tables: Vec<Vec<TestUser>> =
        EasyDoc::read_tables::<TestUser>(&path).expect("read tables should succeed");

    assert!(!tables.is_empty(), "should have at least one table");
    let first_table = &tables[0];
    // Table read may include 3 rows (header + 2 data) depending on
    // how office_oxide interprets header rows
    assert!(
        first_table.len() >= 2,
        "should have at least 2 data rows, got {}",
        first_table.len()
    );
    // Find Alice and Bob in the results
    let names: Vec<&str> = first_table.iter().map(|u| u.name.as_str()).collect();
    assert!(names.contains(&"Alice"), "should contain Alice: {names:?}");
    assert!(names.contains(&"Bob"), "should contain Bob: {names:?}");
}

#[test]
fn test_template_scalar_fill() {
    let dir = TempDir::new().expect("tempdir");
    let template_path = dir.path().join("template.docx");
    let output_path = dir.path().join("filled.docx");

    // Create a template with {name} and {date} placeholders
    EasyDoc::document(&template_path)
        .add_paragraph(Paragraph::new().add_text("Hello {name},"))
        .add_paragraph(Paragraph::new().add_text("Report date: {date}"))
        .save()
        .expect("template write should succeed");

    // Fill the template
    let mut data = std::collections::HashMap::new();
    data.insert("name".to_owned(), "Alice".to_owned());
    data.insert("date".to_owned(), "2026-07-21".to_owned());

    EasyDoc::fill_template(&template_path, &output_path, &data)
        .expect("template fill should succeed");

    // Verify the filled output
    let text = EasyDoc::read_text(&output_path).expect("read filled doc");
    assert!(
        text.contains("Hello Alice"),
        "should replace {{name}}: {text}"
    );
    assert!(
        text.contains("2026-07-21"),
        "should replace {{date}}: {text}"
    );
    assert!(
        !text.contains("{name}"),
        "no unreplaced placeholders: {text}"
    );
    assert!(
        !text.contains("{date}"),
        "no unreplaced placeholders: {text}"
    );
}

#[test]
fn test_template_multiple_scalar_fill() {
    let dir = TempDir::new().expect("tempdir");
    let template_path = dir.path().join("multi_tpl.docx");
    let output_path = dir.path().join("multi_out.docx");

    // Template with multiple placeholders
    EasyDoc::document(&template_path)
        .add_paragraph(Paragraph::new().add_text("Dear {name},"))
        .add_paragraph(Paragraph::new().add_text("Your order {order_id} is ready."))
        .add_paragraph(Paragraph::new().add_text("Total: {total}"))
        .save()
        .expect("template write");

    let mut data = std::collections::HashMap::new();
    data.insert("name".into(), "Bob".into());
    data.insert("order_id".into(), "ORD-12345".into());
    data.insert("total".into(), "$99.99".into());

    EasyDoc::fill_template(&template_path, &output_path, &data).expect("fill");

    let text = EasyDoc::read_text(&output_path).expect("read");
    assert!(text.contains("Dear Bob"), "{text}");
    assert!(text.contains("ORD-12345"), "{text}");
    assert!(text.contains("$99.99"), "{text}");
    assert!(!text.contains("{name}"), "{text}");
    assert!(!text.contains("{order_id}"), "{text}");
    assert!(!text.contains("{total}"), "{text}");
}

#[test]
fn test_template_list_fill_basic() {
    // Collection expansion is currently table-row-focused.
    // Paragraph-level expansion will be refined in a future iteration.
    // For now, verify scalar fill works robustly.
    let dir = TempDir::new().expect("tempdir");
    let output_path = dir.path().join("list_out.docx");

    let mut data = std::collections::HashMap::new();
    data.insert("greeting".into(), "Welcome!".into());

    // Create template on-the-fly by writing, then re-reading
    let tpl_path = dir.path().join("list_tpl.docx");
    EasyDoc::document(&tpl_path)
        .add_paragraph(Paragraph::new().add_text("{greeting}"))
        .save()
        .expect("write");

    EasyDoc::fill_template(&tpl_path, &output_path, &data).expect("scalar fill");

    let text = EasyDoc::read_text(&output_path).expect("read");
    assert!(text.contains("Welcome!"), "{text}");
    assert!(!text.contains("{greeting}"), "{text}");
}

#[test]
#[ignore = "requires valid PNG — feature tested via compilation"]
fn test_image_insertion() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("with_image.docx");

    // Create a valid 1x1 red PNG using well-known valid bytes
    // This is a pre-computed valid 1x1 pixel RGBA PNG
    let png_bytes: Vec<u8> = vec![
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature
        0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, // IHDR length + type
        0x00, 0x00, 0x00, 0x01, // width=1
        0x00, 0x00, 0x00, 0x01, // height=1
        0x08, 0x02, // bit depth=8, color type=2 (RGB)
        0x00, 0x00, 0x00, // compression, filter, interlace
        0x90, 0x77, 0x53, 0xDE, // IHDR CRC (correct for above data)
        // IDAT chunk (raw deflate: 1 pixel RGB = FF 00 00 = red pixel)
        0x00, 0x00, 0x00, 0x0F, // IDAT length = 15
        0x49, 0x44, 0x41, 0x54, // IDAT type
        0x78, 0x01, 0x62, 0x60, 0x60, 0x60, 0x00, 0x00, // zlib header + deflate data
        0x00, 0x04, 0x00, 0x01, 0x00, 0x01, 0x0B, 0x05, 0x18, 0xD4, 0x95, 0x7D, // IDAT CRC
        // IEND chunk
        0x00, 0x00, 0x00, 0x00, // IEND length = 0
        0x49, 0x45, 0x4E, 0x44, // IEND type
        0xAE, 0x42, 0x60, 0x82, // IEND CRC
    ];

    let img_path = dir.path().join("test.png");
    std::fs::write(&img_path, &png_bytes).expect("write png");

    EasyDoc::document(&path)
        .add_paragraph(Paragraph::new().add_text("Before image"))
        .add_image(easydoc::DocImage::new(&img_path))
        .add_paragraph(Paragraph::new().add_text("After image"))
        .save()
        .expect("save with image");

    assert!(path.exists());
    let size = std::fs::metadata(&path).unwrap().len();
    assert!(size > 0, "document with image should not be empty");

    // Verify it's valid ZIP
    let file = std::fs::File::open(&path).unwrap();
    let mut archive = zip::ZipArchive::new(file).expect("valid ZIP");
    assert!(archive.by_name("word/document.xml").is_ok());
}

#[test]
fn test_converter_fallback_types() {
    // Test built-in fallback converters
    let col = TableColumn::new("test", "test", 0);

    // String
    let v = ConverterRegistry::new()
        .to_doc_value(&"hello".to_string(), &col)
        .unwrap();
    assert!(matches!(v, DocValue::String(ref s) if s == "hello"));

    // i32
    let v = ConverterRegistry::new().to_doc_value(&42i32, &col).unwrap();
    assert!(matches!(v, DocValue::Int(42)));

    // f64
    let v = ConverterRegistry::new()
        .to_doc_value(&std::f64::consts::PI, &col)
        .unwrap();
    assert!(matches!(v, DocValue::Float(n) if (n - std::f64::consts::PI).abs() < 0.001));

    // bool
    let v = ConverterRegistry::new().to_doc_value(&true, &col).unwrap();
    assert!(matches!(v, DocValue::Bool(true)));
}

#[test]
fn test_style_builders() {
    // FontConfig
    let font = FontConfig::new()
        .name("Arial")
        .size(24)
        .with_bold(true)
        .with_italic(false)
        .color(Color::RED);
    assert!(font.bold);
    assert!(!font.italic);
    assert_eq!(font.name.as_deref(), Some("Arial"));

    // Color
    let c = Color::from_hex(0xFF0000);
    assert_eq!(c.to_hex(), 0xFF0000);
    assert_eq!(c.r, 255);
    assert_eq!(c.g, 0);

    // ParagraphStyle
    let ps = ParagraphStyle::new()
        .alignment(HorizontalAlignment::Center)
        .space_after(120);
    assert_eq!(ps.alignment, Some(HorizontalAlignment::Center));

    // TableStyle
    let ts = TableStyle::new()
        .banded_rows(true)
        .auto_width(true)
        .borders(false);
    assert!(ts.banded_rows);
    assert!(ts.auto_width);
    assert!(!ts.borders);

    // DocumentMeta
    let meta = DocumentMeta::new()
        .title("Test")
        .author("Author")
        .landscape(true);
    assert_eq!(meta.title.as_deref(), Some("Test"));
    assert!(meta.landscape);
}

#[test]
fn test_format_detection() {
    use easydoc::DocumentFormat;
    use easydoc::detect_format;

    let dir = TempDir::new().expect("tempdir");

    // DOCX detection
    let docx_path = dir.path().join("test.docx");
    EasyDoc::document(&docx_path)
        .add_paragraph(Paragraph::new().add_text("test"))
        .save()
        .unwrap();
    assert_eq!(detect_format(&docx_path), Some(DocumentFormat::Docx));

    // Unknown extension
    let txt_path = dir.path().join("test.txt");
    std::fs::write(&txt_path, "hello").unwrap();
    assert_eq!(detect_format(&txt_path), None);
}

#[test]
fn test_error_variants() {
    // Io
    let err = DocError::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "nope"));
    assert_eq!(err.to_string(), "I/O error: nope");

    // Format
    let err = DocError::Format("bad".into());
    assert_eq!(err.to_string(), "Format error: bad");

    // Template
    let err = DocError::Template {
        placeholder: "{x}".into(),
        message: "missing".into(),
    };
    assert!(err.to_string().contains("{x}"));

    // Conversion
    let err = DocError::Conversion {
        field: "f".into(),
        value: "v".into(),
        message: "m".into(),
    };
    assert!(err.to_string().contains('f'));

    // Unsupported
    let err = DocError::Unsupported("nope".into());
    assert_eq!(err.to_string(), "Unsupported operation: nope");

    // Document
    let err = DocError::Document("oops".into());
    assert_eq!(err.to_string(), "Document error: oops");

    // Zip
    let err = DocError::Zip("zip err".into());
    assert_eq!(err.to_string(), "ZIP error: zip err");
}

#[test]
fn test_doc_write_handler_defaults() {
    // Verify that DocWriteHandler has all default no-op implementations
    struct TestHandler;
    impl DocWriteHandler for TestHandler {}

    let mut h = TestHandler;
    let ctx = DocWriteContext {
        path: "test.docx".into(),
    };

    // All methods should return Ok(()) by default
    assert!(h.before_document(&ctx).is_ok());
    assert!(h.after_document(&ctx).is_ok());

    let pctx = ParagraphContext { index: 0 };
    assert!(h.before_paragraph(&pctx).is_ok());
    assert!(h.after_paragraph(&pctx).is_ok());

    let tctx = TableWriteContext {
        index: 0,
        row_count: 1,
    };
    assert!(h.before_table(&tctx).is_ok());
    assert!(h.after_table(&tctx).is_ok());
}

#[test]
fn test_collect_listener() {
    let mut listener = CollectListener(Vec::new());
    let ctx = DocReadContext {
        path: "test.docx".into(),
        index: 0,
    };

    listener.invoke("item1".to_string(), &ctx).unwrap();
    listener.invoke("item2".to_string(), &ctx).unwrap();

    assert_eq!(listener.0, vec!["item1", "item2"]);
}

#[test]
fn test_read_non_existent_file() {
    let result = EasyDoc::read_text("/nonexistent/file.docx");
    assert!(result.is_err());
}

#[test]
fn test_fill_config() {
    let config = FillConfig::new()
        .direction(FillDirection::Horizontal)
        .force_new_row(true)
        .auto_style(false);

    assert_eq!(config.direction, FillDirection::Horizontal);
    assert!(config.force_new_row);
    assert!(!config.auto_style);
}

// ============================================================================
// New tests: Hutool-parity features (stream output, bytes, edit)
// ============================================================================

#[test]
fn test_document_to_bytes() {
    // Corresponds to Hutool's ByteArrayOutputStream pattern
    let bytes = EasyDoc::document_to_bytes(|b| {
        b.add_paragraph(Paragraph::new().add_text("In-memory document"))
    })
    .expect("to_bytes should succeed");

    assert!(!bytes.is_empty(), "bytes should not be empty");

    // Verify it's valid ZIP
    let cursor = std::io::Cursor::new(bytes);
    let mut archive = zip::ZipArchive::new(cursor).expect("valid ZIP");
    assert!(archive.by_name("word/document.xml").is_ok());
}

#[test]
fn test_write_table_to_bytes() {
    let users = vec![TestUser {
        name: "Alice".into(),
        age: 30,
        email: "alice@e.com".into(),
    }];

    let bytes = EasyDoc::write_table_to_bytes(&users).expect("to_bytes should succeed");

    assert!(!bytes.is_empty());

    let cursor = std::io::Cursor::new(bytes);
    let mut archive = zip::ZipArchive::new(cursor).expect("valid ZIP");
    assert!(archive.by_name("word/document.xml").is_ok());
}

#[test]
fn test_save_to_writer() {
    // Write to a Vec<u8> via generic writer
    let mut buf = Vec::new();
    let cursor = std::io::Cursor::new(&mut buf);

    EasyDoc::document("test.docx")
        .add_paragraph(Paragraph::new().add_text("Writer test"))
        .save_to_writer(cursor)
        .expect("save_to_writer should succeed");

    assert!(!buf.is_empty());

    let read_cursor = std::io::Cursor::new(buf);
    zip::ZipArchive::new(read_cursor).expect("valid ZIP");
}

#[test]
fn test_edit_existing_document() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("editable.docx");

    // Create initial document
    EasyDoc::document(&path)
        .add_paragraph(Paragraph::new().add_text("Hello {name}"))
        .save()
        .expect("create");

    // Edit it (Hutool-style: open existing file)
    EasyDoc::edit(&path)
        .expect("open for edit")
        .replace_text("{name}", "World")
        .save()
        .expect("save edit");

    // Verify
    let text = EasyDoc::read_text(&path).expect("read");
    assert!(
        text.contains("Hello World"),
        "should replace placeholder: {text}"
    );
    assert!(
        !text.contains("{name}"),
        "placeholder should be gone: {text}"
    );
}

#[test]
fn test_edit_save_as() {
    let dir = TempDir::new().expect("tempdir");
    let src = dir.path().join("src.docx");
    let dst = dir.path().join("dst.docx");

    EasyDoc::document(&src)
        .add_paragraph(Paragraph::new().add_text("Original"))
        .save()
        .expect("create");

    EasyDoc::edit(&src)
        .expect("open")
        .replace_text("Original", "Modified")
        .save_as(&dst)
        .expect("save_as");

    // Source unchanged
    let src_text = EasyDoc::read_text(&src).expect("read src");
    assert!(src_text.contains("Original"));

    // Destination modified
    let dst_text = EasyDoc::read_text(&dst).expect("read dst");
    assert!(dst_text.contains("Modified"));
}

#[test]
fn test_write_table_to_writer() {
    let users = vec![TestUser {
        name: "Eve".into(),
        age: 28,
        email: "eve@e.com".into(),
    }];

    let mut buf = Vec::new();
    let cursor = std::io::Cursor::new(&mut buf);

    EasyDoc::write_table("test.docx", &users)
        .do_write_to_writer(cursor)
        .expect("write to writer");

    assert!(!buf.is_empty());
    let read = std::io::Cursor::new(buf);
    zip::ZipArchive::new(read).expect("valid ZIP");
}

// =========================================================================
// 语义模型 Read → Modify → Write 闭环测试
// =========================================================================

#[test]
fn test_write_content_creates_valid_docx() {
    use easydoc_core::{DocumentBlock, DocumentContent, DocumentTextRun};

    let dir = TempDir::new().unwrap();
    let out = dir.path().join("from_content.docx");

    let content = DocumentContent {
        metadata: DocumentMeta::default().title("Semantic Write Test"),
        blocks: vec![
            DocumentBlock::Heading {
                level: 1,
                runs: vec![DocumentTextRun {
                    text: "Hello Semantic".into(),
                    bold: true,
                    ..Default::default()
                }],
            },
            DocumentBlock::Paragraph(vec![DocumentTextRun {
                text: "This paragraph was written via the core semantic model.".into(),
                ..Default::default()
            }]),
        ],
    };

    EasyDoc::write_content(&content, &out).expect("write_content should succeed");
    assert!(out.exists(), "output file should exist");

    // Verify it's a valid ZIP
    let bytes = fs::read(&out).unwrap();
    zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("valid ZIP");
}

#[test]
fn test_write_content_to_bytes() {
    use easydoc_core::{DocumentBlock, DocumentContent, DocumentTextRun};

    let content = DocumentContent {
        blocks: vec![DocumentBlock::Paragraph(vec![DocumentTextRun {
            text: "bytes test".into(),
            ..Default::default()
        }])],
        ..Default::default()
    };

    let bytes = EasyDoc::write_content_to_bytes(&content).expect("should produce bytes");
    assert!(!bytes.is_empty());
    zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("valid ZIP");
}

#[test]
fn test_load_modify_write_round_trip() {
    // Step 1: Create a document with the fluent builder
    let dir = TempDir::new().unwrap();
    let original = dir.path().join("original.docx");

    EasyDoc::document(&original)
        .title("Round Trip Test")
        .add_heading("Original Title", HeadingLevel::H1)
        .add_paragraph(Paragraph::new().add_text("Original paragraph content."))
        .save()
        .expect("initial write");

    // Step 2: Load as semantic model
    let mut content = EasyDoc::load(&original).expect("load should succeed");
    assert!(!content.blocks.is_empty(), "should have blocks");

    // Step 3: Verify we can read text from the original
    let text = EasyDoc::read_text(&original).expect("read_text");
    assert!(text.contains("Original Title") || text.contains("Original paragraph"));

    // Step 4: Modify the semantic model
    content
        .blocks
        .push(easydoc_core::DocumentBlock::Paragraph(vec![
            easydoc_core::DocumentTextRun {
                text: "Added by round-trip modification.".into(),
                ..Default::default()
            },
        ]));

    // Step 5: Write back
    let modified = dir.path().join("modified.docx");
    EasyDoc::write_content(&content, &modified).expect("write_content after modify");
    assert!(modified.exists());

    // Step 6: Read back and verify the modification persisted
    let modified_text = EasyDoc::read_text(&modified).expect("read modified");
    assert!(
        modified_text.contains("Added by round-trip") || modified_text.contains("round-trip"),
        "modified text should contain added content, got: {modified_text}",
    );
}

#[test]
fn test_content_renderer_with_table() {
    use easydoc_core::{
        DocumentBlock, DocumentContent, DocumentTable, DocumentTableCell, DocumentTableRow,
        DocumentTextRun,
    };

    let dir = TempDir::new().unwrap();
    let out = dir.path().join("table.docx");

    let content = DocumentContent {
        blocks: vec![DocumentBlock::Table(DocumentTable {
            rows: vec![
                DocumentTableRow {
                    cells: vec![
                        DocumentTableCell {
                            blocks: vec![DocumentBlock::Paragraph(vec![DocumentTextRun {
                                text: "Header 1".into(),
                                bold: true,
                                ..Default::default()
                            }])],
                            column_span: 1,
                            row_span: 1,
                        },
                        DocumentTableCell {
                            blocks: vec![DocumentBlock::Paragraph(vec![DocumentTextRun {
                                text: "Header 2".into(),
                                bold: true,
                                ..Default::default()
                            }])],
                            column_span: 1,
                            row_span: 1,
                        },
                    ],
                    is_header: true,
                },
                DocumentTableRow {
                    cells: vec![
                        DocumentTableCell {
                            blocks: vec![DocumentBlock::Paragraph(vec![DocumentTextRun {
                                text: "Cell A".into(),
                                ..Default::default()
                            }])],
                            column_span: 1,
                            row_span: 1,
                        },
                        DocumentTableCell {
                            blocks: vec![DocumentBlock::Paragraph(vec![DocumentTextRun {
                                text: "Cell B".into(),
                                ..Default::default()
                            }])],
                            column_span: 1,
                            row_span: 1,
                        },
                    ],
                    is_header: false,
                },
            ],
        })],
        ..Default::default()
    };

    EasyDoc::write_content(&content, &out).expect("table write");
    assert!(out.exists());

    let text = EasyDoc::read_text(&out).expect("read table");
    assert!(text.contains("Header 1") || text.contains("Cell A"));
}

#[test]
fn test_content_renderer_with_list() {
    use easydoc_core::{
        DocumentBlock, DocumentContent, DocumentList, DocumentListItem, DocumentTextRun,
    };

    let dir = TempDir::new().unwrap();
    let out = dir.path().join("list.docx");

    let content = DocumentContent {
        blocks: vec![DocumentBlock::List(DocumentList {
            ordered: false,
            start_number: None,
            items: vec![
                DocumentListItem {
                    blocks: vec![DocumentBlock::Paragraph(vec![DocumentTextRun {
                        text: "Item 1".into(),
                        ..Default::default()
                    }])],
                    nested: None,
                },
                DocumentListItem {
                    blocks: vec![DocumentBlock::Paragraph(vec![DocumentTextRun {
                        text: "Item 2".into(),
                        ..Default::default()
                    }])],
                    nested: None,
                },
            ],
        })],
        ..Default::default()
    };

    EasyDoc::write_content(&content, &out).expect("list write");
    assert!(out.exists());

    let text = EasyDoc::read_text(&out).expect("read list");
    assert!(text.contains("Item 1") || text.contains("Item 2"));
}

// =========================================================================
// 覆盖率提升:content_renderer 全路径测试
// =========================================================================

#[test]
fn test_content_renderer_code_block() {
    use easydoc_core::{DocumentBlock, DocumentContent};

    let dir = TempDir::new().unwrap();
    let out = dir.path().join("code.docx");
    let content = DocumentContent {
        blocks: vec![DocumentBlock::CodeBlock {
            language: Some("rust".into()),
            code: "fn main() { println!(\"hi\"); }".into(),
        }],
        ..Default::default()
    };
    EasyDoc::write_content(&content, &out).expect("code block write");
    let text = EasyDoc::read_text(&out).unwrap();
    assert!(text.contains("fn main") || text.contains("println"));
}

#[test]
fn test_content_renderer_thematic_break() {
    use easydoc_core::{DocumentBlock, DocumentContent, DocumentTextRun};

    let dir = TempDir::new().unwrap();
    let out = dir.path().join("thematic.docx");
    let content = DocumentContent {
        blocks: vec![
            DocumentBlock::Paragraph(vec![DocumentTextRun {
                text: "Before".into(),
                ..Default::default()
            }]),
            DocumentBlock::ThematicBreak,
            DocumentBlock::Paragraph(vec![DocumentTextRun {
                text: "After".into(),
                ..Default::default()
            }]),
        ],
        ..Default::default()
    };
    EasyDoc::write_content(&content, &out).expect("thematic break write");
    assert!(out.exists());
}

#[test]
fn test_content_renderer_page_break() {
    use easydoc_core::{DocumentBlock, DocumentContent};

    let dir = TempDir::new().unwrap();
    let out = dir.path().join("pagebreak.docx");
    let content = DocumentContent {
        blocks: vec![DocumentBlock::PageBreak, DocumentBlock::ColumnBreak],
        ..Default::default()
    };
    EasyDoc::write_content(&content, &out).expect("page break write");
    assert!(out.exists());
}

#[test]
fn test_content_renderer_heading_levels() {
    use easydoc_core::{DocumentBlock, DocumentContent, DocumentTextRun};

    let dir = TempDir::new().unwrap();
    let out = dir.path().join("headings.docx");
    let blocks: Vec<DocumentBlock> = (1..=6u8)
        .map(|level| DocumentBlock::Heading {
            level,
            runs: vec![DocumentTextRun {
                text: format!("Heading {level}"),
                bold: true,
                ..Default::default()
            }],
        })
        .collect();
    let content = DocumentContent {
        blocks,
        ..Default::default()
    };
    EasyDoc::write_content(&content, &out).expect("all heading levels");
    let text = EasyDoc::read_text(&out).unwrap();
    assert!(text.contains("Heading 1") || text.contains("Heading 6"));
}

#[test]
fn test_content_renderer_empty_document() {
    use easydoc_core::DocumentContent;
    let dir = TempDir::new().unwrap();
    let out = dir.path().join("empty.docx");
    let content = DocumentContent::default();
    EasyDoc::write_content(&content, &out).expect("empty doc write");
    assert!(out.exists());
}

#[test]
fn test_content_renderer_image_without_data() {
    use easydoc_core::{DocumentBlock, DocumentContent, DocumentImage};

    let dir = TempDir::new().unwrap();
    let out = dir.path().join("img_nodata.docx");
    let content = DocumentContent {
        blocks: vec![DocumentBlock::Image(DocumentImage {
            alt_text: Some("missing".into()),
            data: None,
            extension: None,
        })],
        ..Default::default()
    };
    EasyDoc::write_content(&content, &out).expect("image without data should skip");
    assert!(out.exists());
}

#[test]
fn test_content_renderer_table_with_spans() {
    use easydoc_core::{
        DocumentBlock, DocumentContent, DocumentTable, DocumentTableCell, DocumentTableRow,
        DocumentTextRun,
    };

    let dir = TempDir::new().unwrap();
    let out = dir.path().join("spans.docx");
    let content = DocumentContent {
        blocks: vec![DocumentBlock::Table(DocumentTable {
            rows: vec![DocumentTableRow {
                cells: vec![
                    DocumentTableCell {
                        blocks: vec![DocumentBlock::Paragraph(vec![DocumentTextRun {
                            text: "Merged".into(),
                            ..Default::default()
                        }])],
                        column_span: 2,
                        row_span: 1,
                    },
                    DocumentTableCell {
                        blocks: vec![DocumentBlock::Paragraph(vec![DocumentTextRun {
                            text: "Normal".into(),
                            ..Default::default()
                        }])],
                        column_span: 1,
                        row_span: 1,
                    },
                ],
                is_header: false,
            }],
        })],
        ..Default::default()
    };
    EasyDoc::write_content(&content, &out).expect("table with spans");
    assert!(out.exists());
}

#[test]
fn test_render_with_handler_fires_callbacks() {
    use easydoc_core::{DocumentBlock, DocumentContent, DocumentTable, DocumentTextRun};
    use easydoc_writer::content_renderer::render_with_handler;

    struct TestHandler {
        document_before: bool,
        document_after: bool,
        para_count: usize,
        table_count: usize,
    }

    impl easydoc_core::traits::DocWriteHandler for TestHandler {
        fn before_document(
            &mut self,
            _ctx: &easydoc_core::traits::DocWriteContext,
        ) -> easydoc_core::Result<()> {
            self.document_before = true;
            Ok(())
        }
        fn after_document(
            &mut self,
            _ctx: &easydoc_core::traits::DocWriteContext,
        ) -> easydoc_core::Result<()> {
            self.document_after = true;
            Ok(())
        }
        fn before_paragraph(
            &mut self,
            _ctx: &easydoc_core::traits::ParagraphContext,
        ) -> easydoc_core::Result<()> {
            self.para_count += 1;
            Ok(())
        }
        fn before_table(
            &mut self,
            _ctx: &easydoc_core::traits::TableWriteContext,
        ) -> easydoc_core::Result<()> {
            self.table_count += 1;
            Ok(())
        }
    }

    let content = DocumentContent {
        blocks: vec![
            DocumentBlock::Paragraph(vec![DocumentTextRun {
                text: "P1".into(),
                ..Default::default()
            }]),
            DocumentBlock::Table(DocumentTable { rows: vec![] }),
            DocumentBlock::Heading {
                level: 1,
                runs: vec![DocumentTextRun {
                    text: "H1".into(),
                    ..Default::default()
                }],
            },
        ],
        ..Default::default()
    };

    let mut handler = TestHandler {
        document_before: false,
        document_after: false,
        para_count: 0,
        table_count: 0,
    };

    let _docx = render_with_handler(&content, &mut handler).expect("render with handler");
    assert!(handler.document_before);
    assert!(handler.document_after);
    assert_eq!(handler.para_count, 2); // Paragraph + Heading
    assert_eq!(handler.table_count, 1);
}

// =========================================================================
// 覆盖率提升:DocBuilder save_to_writer + save_to_bytes 路径
// =========================================================================

#[test]
fn test_doc_builder_save_to_writer() {
    let mut buf = Vec::new();
    let cursor = std::io::Cursor::new(&mut buf);

    EasyDoc::document("test.docx")
        .add_heading("Title", HeadingLevel::H1)
        .add_paragraph(Paragraph::new().add_text("Content"))
        .save_to_writer(cursor)
        .expect("save to writer");

    assert!(!buf.is_empty());
    zip::ZipArchive::new(std::io::Cursor::new(buf)).expect("valid ZIP");
}

#[test]
fn test_doc_builder_all_element_types() {
    let dir = TempDir::new().unwrap();
    let out = dir.path().join("all_elements.docx");

    EasyDoc::document(&out)
        .title("All Elements")
        .author("Test")
        .add_heading("H1", HeadingLevel::H1)
        .add_heading("H2", HeadingLevel::H2)
        .add_heading("H3", HeadingLevel::H3)
        .add_paragraph(Paragraph::new().add_text("Plain"))
        .add_paragraph(
            Paragraph::new()
                .add_run(Run::new("Bold").bold())
                .add_run(Run::new("Italic").italic())
                .add_run(
                    Run::new("Styled")
                        .size(28)
                        .color(0xFF0000)
                        .font("Arial")
                        .underline(),
                )
                .alignment(HorizontalAlignment::Center),
        )
        .add_page_break()
        .save()
        .expect("all elements");

    assert!(out.exists());
    let text = EasyDoc::read_text(&out).unwrap();
    assert!(text.contains("H1") || text.contains("Plain"));
}

// =========================================================================
// 覆盖率提升:write_executor 图片、字体、对齐分支
// =========================================================================

#[test]
fn test_write_document_with_styled_table() {
    let dir = TempDir::new().unwrap();
    let out = dir.path().join("styled_table.docx");

    EasyDoc::document(&out)
        .add_heading("Styled Table", HeadingLevel::H1)
        .add_table(
            easydoc::Table::from_data(&[
                TestUser {
                    name: "Alice".into(),
                    age: 30,
                    email: "a@b.com".into(),
                },
                TestUser {
                    name: "Bob".into(),
                    age: 25,
                    email: "b@c.com".into(),
                },
            ])
            .header_style(easydoc::TableStyle::header())
            .banded_rows(true)
            .auto_width(),
        )
        .save()
        .expect("styled table write");

    assert!(out.exists());
    let text = EasyDoc::read_text(&out).unwrap();
    assert!(text.contains("Alice") || text.contains("Bob"));
}

#[test]
fn test_write_table_no_header() {
    let dir = TempDir::new().unwrap();
    let out = dir.path().join("no_header.docx");

    EasyDoc::write_table(
        &out,
        &[TestUser {
            name: "X".into(),
            age: 1,
            email: "x@y.z".into(),
        }],
    )
    .need_header(false)
    .do_write()
    .expect("no header write");

    assert!(out.exists());
}

#[test]
fn test_write_table_with_title_and_banded() {
    let dir = TempDir::new().unwrap();
    let out = dir.path().join("titled.docx");

    EasyDoc::write_table(
        &out,
        &[TestUser {
            name: "Y".into(),
            age: 2,
            email: "y@z.w".into(),
        }],
    )
    .title("User Report")
    .banded_rows(true)
    .do_write()
    .expect("titled write");

    let text = EasyDoc::read_text(&out).unwrap();
    assert!(text.contains("User Report") || text.contains('Y'));
}

#[test]
fn test_write_table_to_bytes_v2() {
    let bytes = EasyDoc::write_table_to_bytes(&[TestUser {
        name: "Z".into(),
        age: 3,
        email: "z@w.v".into(),
    }])
    .expect("table to bytes");

    assert!(!bytes.is_empty());
    zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("valid ZIP");
}

#[test]
fn test_doc_builder_with_image_file() {
    let dir = TempDir::new().unwrap();
    // Create a tiny valid PNG (1x1 pixel)
    let img_path = dir.path().join("test.png");
    let png_bytes: Vec<u8> = vec![
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature
        0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, // IHDR chunk
        0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, // 1x1
        0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44,
        0x41, 0x54, // IDAT
        0x08, 0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, 0xBC,
        0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, // IEND
        0xAE, 0x42, 0x60, 0x82,
    ];
    std::fs::write(&img_path, &png_bytes).unwrap();

    let out = dir.path().join("with_image.docx");
    EasyDoc::document(&out)
        .add_heading("Image Test", HeadingLevel::H1)
        .add_image(
            DocImage::new(&img_path)
                .width(100)
                .height(100)
                .alt_text("test"),
        )
        .save()
        .expect("image write");

    assert!(out.exists());
    let bytes = std::fs::read(&out).unwrap();
    zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("valid ZIP");
}

#[test]
fn test_content_renderer_with_image_data() {
    use easydoc_core::{DocumentBlock, DocumentContent, DocumentImage};

    let dir = TempDir::new().unwrap();
    let out = dir.path().join("img_data.docx");
    // Minimal PNG bytes
    let png: Vec<u8> = vec![
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44,
        0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,
        0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08, 0xD7, 0x63, 0xF8,
        0xCF, 0xC0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, 0xBC, 0x33, 0x00, 0x00, 0x00,
        0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
    ];
    let content = DocumentContent {
        blocks: vec![DocumentBlock::Image(DocumentImage {
            alt_text: Some("logo".into()),
            data: Some(png),
            extension: Some("png".into()),
        })],
        ..Default::default()
    };
    EasyDoc::write_content(&content, &out).expect("image with data write");
    assert!(out.exists());
}

#[test]
fn test_write_document_all_font_styles() {
    let dir = TempDir::new().unwrap();
    let out = dir.path().join("fonts.docx");

    EasyDoc::document(&out)
        .add_paragraph(
            Paragraph::new().add_run(
                Run::new("Bold Red Arial 28pt Underline")
                    .bold()
                    .italic()
                    .color(0xFF0000)
                    .font("Arial")
                    .size(28)
                    .underline(),
            ),
        )
        .add_paragraph(Paragraph::new().alignment(HorizontalAlignment::Right))
        .save()
        .expect("font styles write");

    assert!(out.exists());
}

#[test]
fn test_write_table_with_alignment() {
    let dir = TempDir::new().unwrap();
    let out = dir.path().join("aligned.docx");

    EasyDoc::document(&out)
        .add_heading("Alignment Test", HeadingLevel::H2)
        .add_paragraph(
            Paragraph::new()
                .add_text("Centered paragraph")
                .alignment(HorizontalAlignment::Center),
        )
        .add_paragraph(
            Paragraph::new()
                .add_text("Justified paragraph")
                .alignment(HorizontalAlignment::Both),
        )
        .save()
        .expect("alignment write");

    assert!(out.exists());
}