Skip to content

Document

Document class, root of the ODF document.

Classes:

Name Description
Document

Abstraction of the ODF document.

TableMarkdown

NamedTuple representing an exported markdown table from a spreadsheet.

Attributes:

Name Type Description
AUTOMATIC_PREFIX
UNDERLINE_LVL

AUTOMATIC_PREFIX module-attribute

AUTOMATIC_PREFIX = 'odfdo_auto_'

UNDERLINE_LVL module-attribute

UNDERLINE_LVL = [
    "=",
    "-",
    ":",
    "`",
    "'",
    '"',
    "~",
    "^",
    "_",
    "*",
    "+",
]

Document

Bases: MDDocument

Abstraction of the ODF document.

Methods:

Name Description
__init__

Initialize a Document.

__repr__
__str__
add_file

Insert a file from a path or a file-like object into the document’s container.

add_page_break_style

Ensure the document contains the style required for a manual page break.

del_part

Mark a part for deletion from the document’s archive.

delete_styles

Remove all style information from content and all styles.

from_dict

Create a new spreadsheet Document from dictionary data.

from_json

Create a new spreadsheet Document from JSON content.

get_cell_background_color

Return the background color of a table cell in an ODS document.

get_cell_style_properties

Return the style properties of a table cell in an ODS document.

get_formated_meta

Return meta information as text, with some formatting.

get_formatted_text

Return a formatted string representation of the document’s content.

get_language

Get the default language of the document from its styles.

get_list_style

Get the list style associated with a given style.

get_parent_style

Get the parent style of a given style.

get_part

Return the bytes of the given part. The path is relative to the

get_parts

Get the names of all available parts within the document’s archive.

get_style

Return the style uniquely identified by its name and family.

get_style_properties

Return the properties of the required style as a dictionary.

get_styled_elements

Search for elements (paragraphs, tables, etc.) using a given style name.

get_styles

Retrieve a list of styles from both content.xml and styles.xml.

get_table_displayed

Return the table:display property of the table’s style.

get_table_style

Return the StyleBase instance associated with the table.

get_type

Get the ODF type (also called class) of this document.

insert_style

Insert the given style object into the document.

merge_styles_from

Copy all styles from another document into this document.

new

Create a new Document from a template.

normalize_tables

Ensure all tables in the document have table:table-column

save

Save the document to a target path or file-like object.

set_language

Set the default language of the document, updating both styles and metadata.

set_part

Set the bytes of a given part within the document’s archive.

set_table_displayed

Set the table:display property of the table’s style.

show_styles

Provide a formatted string summary of styles in the document.

to_dict

Export document table(s) as Python dictionaries.

to_json

Export the values from all tables in the document to JSON format.

to_markdown

Export the document content to Markdown format.

Attributes:

Name Type Description
body Body

Get the body element of the content part.

clone Document

Return an exact, deep copy of the document.

container Container | None
content Content

Get the content part (content.xml) of the document.

language str | None

Get or set the default language of the document.

manifest Manifest

Get the manifest part (manifest.xml) of the document.

meta Meta

Get the meta part (meta.xml) of the document.

mimetype str

Get or set the MIME type of the document.

parts list[str]

Get the names of all available parts within the document’s archive.

path Path | None

Get or set the path of the document’s container.

settings Settings

Get the settings part (settings.xml) of the document.

styles Styles

Get the styles part (styles.xml) of the document.

Source code in odfdo/document.py
 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
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
class Document(MDDocument):
    """Abstraction of the ODF document."""

    def __init__(
        self,
        target: str | bytes | Path | Container | io.BytesIO | None = "text",
    ) -> None:
        """Initialize a Document.

        This can either create a new document from a template or load an
        existing one from a path, file-like object, or Container.

        Args:
            target:
                The source to create or load the document from.
                - If a string like "text", "spreadsheet", "presentation",
                  "drawing", or their file extensions ("odt", "ods", "odp",
                  "odg"), a new document is created from a default template.
                  Note: These templates are not truly empty and may require
                  clearing (e.g., `document.body.clear()`).
                - If a path (str or Path) to an existing ODF file, the file
                  is loaded.
                - If a `Container` object, it is used directly.
                - If a file-like object (`io.BytesIO`), the document is loaded
                  from it.
                - If `None`, an empty container is created.
                - If `bytes`, the content is loaded as a string.

        To create a document from a custom template, use the `Document.new()`
        classmethod instead.

        When creating an “empty” document: the document is a copy of the
        default templates document provided with this library, which, as
        templates, are not really empty. It may be useful to clear the newly
        created document: `document.body.clear()`, or adjust meta information
        like description or language: `document.language = 'fr-FR'`.

        """
        # Cache of XML parts
        self.__xmlparts: dict[str, XmlPart] = {}
        # Cache of the body
        self.__body: Element | None = None
        self.container: Container | None = None
        if isinstance(target, bytes):
            # eager conversion
            target = bytes_to_str(target)
        if target is None:
            # empty document, you probably don't want this.
            self.container = Container()
            return
        if isinstance(target, Path):
            # let's assume we open a container on existing file
            self.container = Container(target)
            return
        if isinstance(target, Container):
            # special internal case, use an existing container
            self.container = target
            return
        if isinstance(target, str):
            if target in ODF_TEMPLATES:
                # assuming a new document from templates
                self.container = _container_from_template(target)
                return
            # let's assume we open a container on existing file
            self.container = Container(target)
            return
        if isinstance(target, io.BytesIO):
            self.container = Container(target)
            return
        msg = f"Unknown Document source type: {target!r}"
        raise TypeError(msg)

    def __repr__(self) -> str:
        return f"<{self.__class__.__name__} type={self.get_type()} path={self.path}>"

    def __str__(self) -> str:
        try:
            return str(self.get_formatted_text())
        except NotImplementedError:
            return str(self.body)

    @classmethod
    def new(cls, template: str | Path | io.BytesIO = "text") -> Document:
        """Create a new Document from a template.

        Args:
            template: The template to use.
                - If a string like "text", "spreadsheet", etc., a default
                  template is used.
                - If a path to a custom template file, that template is used.
                - If a file-like object, the template is read from it.

        Returns:
            Document: A new Document instance based on the template.

        """
        container = _container_from_template(template)
        return cls(container)

    # Public API

    @property
    def path(self) -> Path | None:
        """Get or set the path of the document's container.

        When getting, it returns the `Path` object of the container, or `None`
        if the container is not set.

        When setting, it accepts a string or `Path` object to update the
        container's path.

        Returns:
            The `Path` object of the container, or `None` if the container is not set.

        """
        if not self.container:
            return None
        return self.container.path

    @path.setter
    def path(self, path_or_str: str | Path) -> None:
        if not self.container:
            return
        self.container.path = Path(path_or_str)

    def get_parts(self) -> list[str]:
        """Get the names of all available parts within the document's archive.

        This is a helper method for the `parts` property.

        Returns:
            A list of strings, where each string is the path of a part.

        Raises:
            ValueError: If the document's container is empty.

        """
        if not self.container:
            msg = "Empty Container"
            raise ValueError(msg)
        return self.container.parts

    @property
    def parts(self) -> list[str]:
        """Get the names of all available parts within the document's archive.

        The paths are relative to the archive root, e.g.,
        'content.xml', 'Pictures/100000000000032000000258912EB1C3.jpg'.

        This is a convenience property that calls `get_parts()`.

        Returns:
            A list of strings, where each string is the path of a part.

        """
        return self.get_parts()

    def get_part(self, path: str) -> XmlPart | str | bytes | None:
        """Return the bytes of the given part. The path is relative to the
        archive, e.g. "Pictures/1003200258912EB1C3.jpg".

        'content', 'meta', 'settings', 'styles' and 'manifest' are shortcuts to
        the real path, e.g. content.xml, and return a dedicated object with its
        own API.

        The path parameter is formatted as URI, so always use '/' separator.

        Args:
            path: relative path or one of 'content', 'meta', 'settings',
                'styles' or 'manifest'.

        Returns:
             XmlPart | str | bytes | None: the part content.

        """
        if not self.container:
            msg = "Empty Container"
            raise ValueError(msg)
        # "./ObjectReplacements/Object 1"
        path = path.lstrip("./")
        path = _get_part_path(path)
        cls = _get_part_class(path)
        # Raw bytes
        if cls is None:
            return self.container.get_part(path)
        # XML part
        part = self.__xmlparts.get(path)
        if part is None:
            self.__xmlparts[path] = part = cls(path, self.container)
        return part

    def set_part(self, path: str, data: bytes) -> None:
        """Set the bytes of a given part within the document's archive.

        This method updates the content of an existing part or adds a new part
        to the document.

        Args:
            path: The path of the part relative to the archive, e.g.,
                "Pictures/image.jpg". Shortcuts like "content", "meta",
                "settings", "styles", and "manifest" are also supported.
                The path should use '/' as a separator.
            data: The `bytes` object containing the content to set for the part.

        Raises:
            ValueError: If the document's container is empty.

        """
        if not self.container:
            msg = "Empty Container"
            raise ValueError(msg)
        # "./ObjectReplacements/Object 1"
        path = path.lstrip("./")
        path = _get_part_path(path)
        cls = _get_part_class(path)
        # XML part overwritten
        if cls is not None:
            with contextlib.suppress(KeyError):
                del self.__xmlparts[path]
        self.container.set_part(path, data)

    def del_part(self, path: str) -> None:
        """Mark a part for deletion from the document's archive.

        This method marks a specified part for deletion from the ODF document.
        The actual deletion occurs when the document is saved.

        Args:
            path: The path of the part relative to the archive, e.g.,
                "Pictures/1003200258912EB1C3.jpg". Shortcuts like "content"
                are also supported.

        Raises:
            ValueError: If the document's container is empty, or if an attempt
                is made to delete a mandatory part (e.g., "manifest.xml").

        """
        if not self.container:
            msg = "Empty Container"
            raise ValueError(msg)
        path = _get_part_path(path)
        cls = _get_part_class(path)
        if path == ODF_MANIFEST or cls is not None:
            msg = f"part '{path}' is mandatory"
            raise ValueError(msg)
        self.container.del_part(path)

    @property
    def mimetype(self) -> str:
        """Get or set the MIME type of the document.

        When getting, it returns the MIME type as a string (e.g.,
        "application/vnd.oasis.opendocument.text").

        When setting, it accepts a new MIME type as a string.

        Returns:
            The MIME type as a string.

        Raises:
            ValueError: If the document's container is empty.

        """
        if not self.container:
            msg = "Empty Container"
            raise ValueError(msg)
        return self.container.mimetype

    @mimetype.setter
    def mimetype(self, mimetype: str) -> None:
        if not self.container:
            msg = "Empty Container"
            raise ValueError(msg)
        self.container.mimetype = mimetype

    def get_type(self) -> str:
        """Get the ODF type (also called class) of this document.

        Returns: 'chart', 'database', 'formula', 'graphics',
            'graphics-template', 'image', 'presentation',
            'presentation-template', 'spreadsheet', 'spreadsheet-template',
            'text', 'text-master', 'text-template' or 'text-web'
        """
        # The mimetype must be with the form:
        # application/vnd.oasis.opendocument.text

        # Isolate and return the last part
        return self.mimetype.rsplit(".", 1)[-1]

    @property
    def body(self) -> Body:
        """Get the body element of the content part.

        The body element is where the actual content of the ODF document
        (e.g., paragraphs, tables, images) is stored.

        Returns:
            The `Body` element of the document's content part.

        Raises:
            ValueError: If the content part is missing or the body element cannot be retrieved.

        """
        if self.__body is None:
            self.__body = self.content.body
        return self.__body  # ty: ignore[invalid-return-type]

    @property
    def meta(self) -> Meta:
        """Get the meta part (meta.xml) of the document.

        The meta part stores metadata about the document, such as author,
        creation date, and modification date.

        Returns:
            The `Meta` object representing the document's metadata.

        Raises:
            ValueError: If the metadata part is empty or cannot be retrieved as a `Meta` object.

        """
        metadata = self.get_part(ODF_META)
        if metadata is None or not isinstance(metadata, Meta):
            msg = "Empty Meta"
            raise ValueError(msg)
        return metadata

    @property
    def manifest(self) -> Manifest:
        """Get the manifest part (manifest.xml) of the document.

        The manifest lists all files within the ODF package and their MIME types.

        Returns:
            The `Manifest` object representing the document's manifest.

        Raises:
            ValueError: If the manifest part is empty or cannot be retrieved as a `Manifest` object.

        """
        manifest = self.get_part(ODF_MANIFEST)
        if manifest is None or not isinstance(manifest, Manifest):
            msg = "Empty Manifest"
            raise ValueError(msg)
        return manifest

    @property
    def settings(self) -> Settings:
        """Get the settings part (settings.xml) of the document.

        The settings part stores document-wide configuration and preferences.

        Returns:
            Settings: The `Settings` object representing the document's settings.

        Raises:
            ValueError: If the settings part is empty or cannot be retrieved.

        """
        settings_part = self.get_part(ODF_SETTINGS)
        if settings_part is None or not isinstance(settings_part, Settings):
            msg = "Empty settings part"
            raise ValueError(msg)
        return settings_part

    def _get_formatted_text_footnotes(
        self,
        result: list[str],
        context: dict,
        rst_mode: bool,
    ) -> None:
        # Separate text from notes
        if rst_mode:
            result.append("\n")
        else:
            result.append("----\n")
        for citation, body in context["footnotes"]:
            if rst_mode:
                result.append(f".. [#] {body}\n")
            else:
                result.append(f"[{citation}] {body}\n")
        # Append a \n after the notes
        result.append("\n")
        # Reset for the next paragraph
        context["footnotes"] = []

    def _get_formatted_text_annotations(
        self,
        result: list[str],
        context: dict,
        rst_mode: bool,
    ) -> None:
        # Insert the annotations
        # With a separation
        if rst_mode:
            result.append("\n")
        else:
            result.append("----\n")
        for annotation in context["annotations"]:
            if rst_mode:
                result.append(f".. [#] {annotation}\n")
            else:
                result.append(f"[*] {annotation}\n")
        context["annotations"] = []

    def _get_formatted_text_images(
        self,
        result: list[str],
        context: dict,
        rst_mode: bool,
    ) -> None:
        # Insert the images ref, only in rst mode
        result.append("\n")
        for ref, filename, (width, height) in context["images"]:
            result.append(f".. {ref} image:: {filename}\n")
            if width is not None:
                result.append(f"   :width: {width}\n")
            if height is not None:
                result.append(f"   :height: {height}\n")
        context["images"] = []

    def _get_formatted_text_endnotes(
        self,
        result: list[str],
        context: dict,
        rst_mode: bool,
    ) -> None:
        # Append the end notes
        if rst_mode:
            result.append("\n\n")
        else:
            result.append("\n========\n")
        for citation, body in context["endnotes"]:
            if rst_mode:
                result.append(f".. [*] {body}\n")
            else:
                result.append(f"({citation}) {body}\n")

    def get_formatted_text(self, rst_mode: bool = False) -> str:
        """Return a formatted string representation of the document's content.

        For text-based documents, this includes handling of footnotes, annotations,
        and image references. For spreadsheets, it returns a CSV representation.

        Args:
            rst_mode: If True, formats the output in reStructuredText (RST)
                syntax, especially for footnotes and annotations.

        Returns:
            str: The formatted text content of the document.

        Raises:
            NotImplementedError: If the document type is not supported for
                formatted text extraction.

        """
        # For the moment, only "type='text'"
        doc_type = self.get_type()
        if doc_type == "spreadsheet":
            return self._tables_csv()
        if doc_type in {
            "text",
            "text-template",
            "presentation",
            "presentation-template",
        }:
            return self._formatted_text(rst_mode)
        msg = f"Type of document {doc_type!r} not supported yet"
        raise NotImplementedError(msg)

    def _tables_csv(self) -> str:
        return "\n\n".join(str(table) for table in self.body.tables)

    def _formatted_text(self, rst_mode: bool) -> str:
        # Initialize an empty context
        context = {
            "document": self,
            "footnotes": [],
            "endnotes": [],
            "annotations": [],
            "rst_mode": rst_mode,
            "img_counter": 0,
            "images": [],
            "no_img_level": 0,
        }
        body = self.body
        # Get the text
        result = []
        for child in body.children:
            # self._get_formatted_text_child(result, element, context, rst_mode)
            # if child.tag == "table:table":
            #     result.append(child.get_formatted_text(context))
            #     return
            result.append(child.get_formatted_text(context))
            if context["footnotes"]:
                self._get_formatted_text_footnotes(result, context, rst_mode)
            if context["annotations"]:
                self._get_formatted_text_annotations(result, context, rst_mode)
            # Insert the images ref, only in rst mode
            if context["images"]:
                self._get_formatted_text_images(result, context, rst_mode)
        if context["endnotes"]:
            self._get_formatted_text_endnotes(result, context, rst_mode)
        return "".join(result)

    def get_formated_meta(self) -> str:
        """Return meta information as text, with some formatting.

        (Redirection to new implementation for compatibility.)

        Returns:
            A formatted string containing the document's metadata.

        """
        return self.meta.as_text()

    def to_markdown(self) -> str | list[TableMarkdown]:
        """Export the document content to Markdown format.

        For text documents (.odt), returns a single Markdown string.
        For spreadsheet documents (.ods), returns a list of TableMarkdown
        tuples (one per table) containing the filename and Markdown table
        string.

        Returns:
            str | list[TableMarkdown]: The Markdown representation of the
                document for text documents, or a list of TableMarkdown tuples
                for spreadsheets.

        Raises:
            NotImplementedError: If the document type is not 'text' or
                'spreadsheet'.

        """
        doc_type = self.get_type()
        if doc_type not in {"text", "spreadsheet"}:
            msg = f"Type of document {doc_type!r} not supported yet"
            raise NotImplementedError(msg)
        if doc_type == "text":
            return self._markdown_export_text()
        return self._markdown_export_tables()

    def _markdown_export_tables(self) -> list[TableMarkdown]:
        doc_stem = self.path.stem if self.path else "spreadsheet"
        doc_stem = doc_stem.replace(" ", "_")
        tables = self.body.tables
        unifyer = NameUnifyer()
        results: list[TableMarkdown] = []
        _set_global(self)
        try:
            for table in tables:
                raw_table_name = table.name or ""
                table_name = raw_table_name.replace(" ", "_")
                unique_name = unifyer.unique(table_name)
                identifier = f"{doc_stem}#{unique_name}"
                content = table.to_markdown()
                results.append(TableMarkdown(identifier, content))
        finally:
            _set_global(None)
        return results

    def to_json(
        self,
        path_or_file: str | Path | None = None,
        include_hidden: bool = False,
        pretty: bool = False,
        ensure_ascii: bool = False,
    ) -> str | None:
        """Export the values from all tables in the document to JSON format.

        The JSON output is a dictionary mapping each table's name to its 2D
        list of cell values (list of list of cell values).

        Args:
            path_or_file: The path or file to save the JSON content to.
                If None, the JSON content is returned as a string.
            include_hidden: If True, include hidden tables in the export.
                Defaults to False.
            pretty: Use pretty formater. Defaults to False.
            ensure_ascii: If True, non-ASCII characters are escaped.
                Defaults to False.

        Returns:
            str | None: The JSON content as a string if `path_or_file` is
                None, otherwise None.

        """
        tables_dict: dict[str, list[list[Any]]] = {}
        unifyer = NameUnifyer()

        for table in self.body.tables:
            if not include_hidden and not self.get_table_displayed(table):
                continue
            name = unifyer.unique(table.name or "")
            tables_dict[name] = serialize_table(table, "json")

        if pretty:
            content_str = format_json(tables_dict, ensure_ascii=ensure_ascii)
        else:
            content_str = json.dumps(
                tables_dict, ensure_ascii=ensure_ascii, allow_nan=False
            )

        if path_or_file:
            Path(path_or_file).write_text(content_str, encoding="utf-8")
            return None
        return content_str

    @classmethod
    def from_json(
        cls,
        content: str | Path | dict[str, list[list[Any]]],
        table_name: str = "",
    ) -> Document:
        """Create a new spreadsheet Document from JSON content.

        Args:
            content: A JSON string, a Path or filename to a JSON file, or a
                dictionary mapping table names to 2D lists of cell values.
            table_name: Name of the table if the input is a list.

        Returns:
            Document: A new spreadsheet Document containing Table elements
                for each table in the JSON content.

        Raises:
            TypeError: If content is not a string, Path, or dict, or if the
                decoded JSON structure is not a dictionary.

        """
        data: Any
        if isinstance(content, Path):
            data = json.loads(content.read_text(encoding="utf-8"))
        elif isinstance(content, str):
            with contextlib.suppress(OSError, ValueError):
                if Path(content).is_file():
                    content = Path(content).read_text(encoding="utf-8")
            data = json.loads(content)
        elif isinstance(content, dict | list):
            data = content
        else:
            msg = "JSON content must be a string, Path, dict or list"
            raise TypeError(msg)

        if not isinstance(data, dict | list):
            msg = (
                "JSON document content must be a dictionary mapping "
                "table names to row lists or a list of rows"
            )
            raise TypeError(msg)

        doc = cls.new("spreadsheet")
        body = doc.body
        body.clear()

        if isinstance(data, dict):
            for t_name, rows in data.items():
                table = Table(t_name)
                table.clear()
                body.append(table)
                _populate_table(table, rows)
        else:  # list
            unifyer = NameUnifyer()
            name = unifyer.unique(table_name)
            table = Table(name)
            table.clear()
            body.append(table)
            _populate_table(table, data)

        return doc

    def to_dict(
        self,
        table: str | int | None = None,
        orient: str = "list",
        header: bool = True,
        mode: str = "python",
        lstrip: bool = False,
        include_hidden: bool = False,
        no_decimal: bool = False,
        no_date: bool = False,
        no_nan: bool = False,
    ) -> dict[str, Any] | list[dict[str, Any]]:
        """Export document table(s) as Python dictionaries.

        Args:
            table: Name or 0-based index of a specific table to export. If
                None, exports all tables in the document.
            orient: Format of the exported dictionary:
                - "list" (default): Columnar format `{"col": [values, ...]}`.
                - "records": List of row dicts `[{"col": value, ...}, ...]`.
                - "matrix": Dict mapping table names to 2D lists
                  `{"TableName": [[...], ...]}`.
            header: If True, uses the first row of data as column header keys.
            mode: Serialization mode ("python" or "json"). Defaults to
                "python". "python" mode can be customized by arguments
                "no_decimal", "no_date" and "no_nan".
            lstrip: If True, removes leading empty rows and columns from the
                top-left before export.
            include_hidden: If True, include hidden tables.
            no_decimal: If True in "python" mode, convert Decimal values to
                float or int.
            no_date: If True in "python" mode, convert date, datetime, and
                timedelta values to ODF/ISO formatted strings.
            no_nan: If True in "python" mode, convert NaN and infinity values
                to None.

        Example:
            Table "product":

            | reference | color | price |
            |-----------|-------|-------|
            | ref01     | white | 10,00 |
            | ref02     | blue  | 20,50 |
            | ref03     | red   | 25,75 |

        >>> document.to_dict()
        {
            'product': {
                'reference': ['ref01', 'ref02', 'ref03'],
                'color': ['white', 'blue', 'red'],
                'price': [10, Decimal('20.5'), Decimal('25.75')]
            }
        }

        >>> document.to_dict(orient="records")
        {
            'product': [
                {'reference': 'ref01', 'color': 'white', 'price': 10},
                {'reference': 'ref02', 'color': 'blue', 'price': Decimal('20.5')},
                {'reference': 'ref03', 'color': 'red', 'price': Decimal('25.75')}
            ]
        }

        >>> document.to_dict(orient="matrix")
        {
            'product': [
                ['reference', 'color', 'price'],
                ['ref01', 'white', 10],
                ['ref02', 'blue', Decimal('20.5')],
                ['ref03', 'red', Decimal('25.75')]
            ]
        }

        Returns:
            A dictionary of table dictionaries if `table` is None, or the
            dictionary for the specified table if `table` is given.

        Raises:
            KeyError: If the specified table name is not found.
            IndexError: If the specified table index is out of bounds.
            ValueError: If `orient` is not one of "list", "records", or "matrix".

        """
        if orient not in ("list", "records", "matrix"):
            msg = (
                f"Invalid orient parameter: {orient!r}. "
                "Expected 'list', 'records', or 'matrix'"
            )
            raise ValueError(msg)
        if table is not None:
            if isinstance(table, int):
                tables = self.body.tables
                if table < 0 or table >= len(tables):
                    msg = f"Table index {table} out of range (0..{len(tables) - 1})"
                    raise IndexError(msg)
                target_table = tables[table]
            else:
                target_table = self.body.get_table_by_name(table)
                if not target_table:
                    msg = f"Table {table!r} not found in document"
                    raise KeyError(msg)
            return target_table.to_dict(
                orient=orient,
                header=header,
                mode=mode,
                lstrip=lstrip,
                no_decimal=no_decimal,
                no_date=no_date,
                no_nan=no_nan,
            )

        tables_dict: dict[str, Any] = {}
        unifyer = NameUnifyer()
        for t in self.body.tables:
            if not include_hidden and not self.get_table_displayed(t):
                continue
            name = unifyer.unique(t.name or "")
            table_dict = t.to_dict(
                orient=orient,
                header=header,
                mode=mode,
                lstrip=lstrip,
                no_decimal=no_decimal,
                no_date=no_date,
                no_nan=no_nan,
            )
            if orient == "matrix" and isinstance(table_dict, dict):
                tables_dict[name] = (
                    next(iter(table_dict.values())) if table_dict else []
                )
            else:
                tables_dict[name] = table_dict
        return tables_dict

    @classmethod
    def from_dict(
        cls,
        data: dict[str, Any] | list[dict[str, Any]],
        table_name: str | None = None,
        guess_type: bool = False,
        language: str | None = None,
    ) -> Document:
        """Create a new spreadsheet Document from dictionary data.

        Accepts:
        - Multi-sheet dict: `{"Sheet1": data1, "Sheet2": data2}`
        - Single table data (dict of columns, list of record dicts, or matrix)

        Args:
            data: The dictionary or list of dicts to import.
            table_name: Optional name for single-table import.
            guess_type: If True, try to detect Python type from strings
                values (int, float, dates).
            language: Optional document language code.

        Example:
            # Multi-sheet: columnar format
            >>> data = {
            ...     "product": {
            ...         "reference": ["ref01", "ref02"],
            ...         "price": [10, 20.5],
            ...     },
            ...     "stock": {
            ...         "reference": ["ref01", "ref02"],
            ...         "qty": [100, 50],
            ...     },
            ... }
            >>> doc = Document.from_dict(data)

            # Multi-sheet: records format
            >>> data = {
            ...     "product": [
            ...         {"reference": "ref01", "price": 10},
            ...         {"reference": "ref02", "price": 20.5},
            ...     ],
            ...     "stock": [
            ...         {"reference": "ref01", "qty": 100},
            ...         {"reference": "ref02", "qty": 50},
            ...     ],
            ... }
            >>> doc = Document.from_dict(data)

            # Multi-sheet: matrix format
            >>> data = {
            ...     "product": [
            ...         ["reference", "price"],
            ...         ["ref01", 10],
            ...         ["ref02", 20.5],
            ...     ],
            ...     "stock": [
            ...         ["reference", "qty"],
            ...         ["ref01", 100],
            ...         ["ref02", 50],
            ...     ],
            ... }
            >>> doc = Document.from_dict(data)

            # Single table: columnar dict
            >>> data = {
            ...     "reference": ["ref01", "ref02"],
            ...     "price": [10, 20.5],
            ... }
            >>> doc = Document.from_dict(data, table_name="product")

            # Single table: list of records
            >>> data = [
            ...     {"reference": "ref01", "price": 10},
            ...     {"reference": "ref02", "price": 20.5},
            ... ]
            >>> doc = Document.from_dict(data, table_name="product")

        Returns:
            Document: A new spreadsheet Document populated with the tables.

        Raises:
            TypeError: If data is not a dict or list of dicts.

        """
        doc = cls.new("spreadsheet")
        doc.body.clear()
        unifyer = NameUnifyer()

        if isinstance(data, dict):
            if not data:
                name = unifyer.unique(table_name or "")
                doc.body.append(Table.from_dict({}, name=name))
            else:
                first_val = next(iter(data.values()))
                if isinstance(first_val, dict) or (
                    isinstance(first_val, list)
                    and (
                        (
                            len(data) > 1
                            and (
                                not first_val or isinstance(first_val[0], (dict, list))
                            )
                        )
                        or (
                            len(data) == 1
                            and bool(first_val)
                            and isinstance(first_val[0], dict)
                        )
                    )
                ):
                    for name, sheet_data in data.items():
                        unique_name = unifyer.unique(name or "")
                        if isinstance(sheet_data, list) and (
                            not sheet_data or isinstance(sheet_data[0], list)
                        ):
                            table = Table.from_dict(
                                {unique_name: sheet_data},
                                name=unique_name,
                                guess_type=guess_type,
                            )
                        else:
                            table = Table.from_dict(
                                sheet_data,
                                name=unique_name,
                                guess_type=guess_type,
                            )
                        doc.body.append(table)
                else:
                    # Single table (columnar dict or single matrix)
                    if (
                        len(data) == 1
                        and isinstance(first_val, list)
                        and (not first_val or isinstance(first_val[0], list))
                    ):
                        name = table_name
                    else:
                        name = unifyer.unique(table_name or "")
                    table = Table.from_dict(
                        data,
                        name=name,
                        guess_type=guess_type,
                    )
                    doc.body.append(table)
        elif isinstance(data, list):
            name = unifyer.unique(table_name or "")
            table = Table.from_dict(
                data,
                name=name,
                guess_type=guess_type,
            )
            doc.body.append(table)
        else:
            msg = "Data must be a dict or list of dicts"
            raise TypeError(msg)

        if language:
            doc.language = language

        return doc

    def _add_binary_part(self, blob: Blob) -> str:
        if not self.container:
            msg = "Empty Container"
            raise ValueError(msg)
        manifest = self.manifest
        if manifest.get_media_type("Pictures/") is None:
            manifest.add_full_path("Pictures/")
        path = posixpath.join("Pictures", blob.name)
        self.container.set_part(path, blob.content)
        manifest.add_full_path(path, blob.mime_type)
        return path

    def add_file(self, path_or_file: str | Path | BinaryIO) -> str:
        """Insert a file from a path or a file-like object into the document's container.

        The internal name of the file in the "Pictures/" folder is generated
        by a hash function. The method returns the full path (URI) that can be
        used to reference the added file within the document's content.

        Args:
            path_or_file: The path to the file (str or Path) or a file-like
                object (`BinaryIO`) containing the file's content.

        Returns:
            The full path (URI) to reference the added file in the content.

        Raises:
            ValueError: If the document's container is empty.

        """
        if not self.container:
            msg = "Empty Container"
            raise ValueError(msg)
        if isinstance(path_or_file, (str, Path)):
            blob = Blob.from_path(path_or_file)
        else:
            blob = Blob.from_io(path_or_file)
        return self._add_binary_part(blob)

    @property
    def clone(self) -> Document:
        """Return an exact, deep copy of the document.

        All internal structures, including the container and its parts,
        are duplicated.

        Returns:
            A new `Document` instance that is a deep copy of the original.

        Raises:
            ValueError: If the original document's container is empty.

        """
        clone = object.__new__(self.__class__)
        for name in self.__dict__:
            if name == "_Document__body":
                setattr(clone, name, None)
            elif name == "_Document__xmlparts":
                setattr(clone, name, {})
            elif name == "container":
                if not self.container:
                    msg = "Empty Container"
                    raise ValueError(msg)
                setattr(clone, name, self.container.clone)
            else:
                value = deepcopy(getattr(self, name))
                setattr(clone, name, value)
        return clone

    def _check_manifest_rdf(self) -> None:
        if not self.container:
            return
        manifest = self.manifest
        parts = self.container.parts
        if manifest.get_media_type(ODF_MANIFEST_RDF):
            if ODF_MANIFEST_RDF not in parts:
                self.container.set_part(
                    ODF_MANIFEST_RDF, self.container.default_manifest_rdf.encode("utf8")
                )
        else:
            if ODF_MANIFEST_RDF in parts:
                self.container.del_part(ODF_MANIFEST_RDF)

    def _ensure_odf14(self) -> None:
        """Upgrade older ODF documents to ODF 1.4 and create missing core
        parts.

        Existing XML parts get their `office:version` attribute set to "1.4".
        Missing core parts (`content.xml`, `styles.xml`, `meta.xml`,
        `settings.xml`) are copied from the default template for the document
        type and added to the manifest.

        Note:
            The ODF 1.4 specification keeps the same namespace URIs as earlier
            versions for the core vocabularies, so only the `office:version`
            attribute needs to change; missing extension namespace declarations
            are added implicitly when those prefixes are actually used.

        """
        if not self.container:
            return
        if ODF_CONTENT not in self.container.parts:
            # Too broken to fix automatically.
            return
        content_part = self.get_part(ODF_CONTENT)
        if content_part is None or not isinstance(content_part, XmlPart):
            return
        current_version = content_part.root.get_attribute("office:version")
        all_parts_present = all(
            path in self.container.parts
            for path in (ODF_META, ODF_SETTINGS, ODF_STYLES)
        )
        if current_version == OFFICE_VERSION and all_parts_present:
            return

        doc_type = self.get_type()
        template_container = _template_container(doc_type)
        manifest = self.get_part(ODF_MANIFEST)
        if not isinstance(manifest, Manifest):
            return
        for path in (ODF_CONTENT, ODF_META, ODF_SETTINGS, ODF_STYLES):
            part = self.__xmlparts.get(path)
            if part is None and path not in self.container.parts:
                if template_container is None:
                    continue
                raw_data = template_container.get_part(path)
                if raw_data is None:
                    continue
                template_data = (
                    raw_data.encode("utf-8") if isinstance(raw_data, str) else raw_data
                )
                self.container.set_part(path, template_data)
                manifest.add_full_path(path, "text/xml")
                part = self.get_part(path)
            elif part is None:
                part = self.get_part(path)
            if part is not None and isinstance(part, XmlPart):
                part.root.set_attribute("office:version", OFFICE_VERSION)
        # Keep manifest:version in sync with office:version. LibreOffice is
        # strict about this attribute and may report a corrupt document when
        # office:version is "1.4" but manifest:version is still "1.3".
        manifest.root.set_attribute("manifest:version", OFFICE_VERSION)
        root_entry = manifest.root.get_element(
            "//manifest:file-entry[@manifest:full-path='/']"
        )
        if root_entry is not None:
            root_entry.set_attribute("manifest:version", OFFICE_VERSION)
        self.container.set_part(ODF_MANIFEST, manifest.serialize())

    def normalize_tables(self) -> None:
        """Ensure all tables in the document have table:table-column
        definitions covering the full width of their rows.
        """
        if not self.container:
            return
        tables: list[Table] = []
        with contextlib.suppress(ValueError, AttributeError, TypeError):
            tables.extend(self.body.get_tables())
        styles = self.get_part(ODF_STYLES)
        if isinstance(styles, XmlPart):
            tables.extend(
                elem
                for elem in styles.get_elements("//table:table")
                if isinstance(elem, Table)
            )
        for table in tables:
            table.normalize_columns()

    def save(
        self,
        target: str | Path | io.BytesIO | None = None,
        packaging: str = ZIP,
        pretty: bool | None = None,
        backup: bool = False,
    ) -> None:
        """Save the document to a target path or file-like object.

        The document can be saved at its original location, or to a new path
        or file-like object. It can be saved as a Zip file (default),
        flat XML format, or as files in a folder (for debugging purposes).
        XML parts can be pretty printed.

        Note: 'xml' packaging is an experimental work in progress.

        Args:
            target: The destination to save the document to. Can be a string
                path, a `Path` object, or a file-like object (`io.BytesIO`).
                If `None`, the document is saved to its original path.
            packaging: The packaging format: 'zip' (default), 'folder', or 'xml'.
            pretty: If `True`, XML parts will be pretty-printed. If `None` (default),
                it defaults to `True` for 'folder' and 'xml' packaging.
            backup: If `True`, a backup of the existing file will be created
                before saving.

        Raises:
            ValueError: If the document's container is empty or an unsupported
                packaging type is specified.
            RuntimeError: In unexpected scenarios during XML part handling.

        """
        if not self.container:
            msg = "Empty Container"
            raise ValueError(msg)
        if packaging not in PACKAGING:
            msg = f"Packaging of type {packaging!r} is not supported"
            raise ValueError(msg)
        if target is None and self.path is None:
            msg = "Saving a document without path requires a target"
            raise ValueError(msg)
        # Some advertising
        if packaging != FOLDER:
            self.meta.set_generator_default()
        # Synchronize data with container
        container = self.container
        if pretty is None:
            pretty = packaging in {"folder", "xml"}
        pretty = bool(pretty)
        backup = bool(backup)
        # Folder packaging is intended for debugging/analysis: preserve the
        # original parts (version, missing files, manifest.rdf, table columns)
        # as much as possible, but still pretty-print XML when requested.
        if packaging != FOLDER:
            self._ensure_odf14()
            self._check_manifest_rdf()
            self.normalize_tables()
        if pretty and packaging != XML:
            for path, part in self.__xmlparts.items():
                if part is not None:
                    container.set_part(path, part.pretty_serialize())
            for path in (ODF_CONTENT, ODF_META, ODF_SETTINGS, ODF_STYLES):
                if path in self.__xmlparts:
                    continue
                # Only create and serialize the part if it exists in the container
                if path not in container.parts:
                    continue
                cls = _get_part_class(path)
                if cls is None:
                    msg = "Should never happen"
                    raise RuntimeError(msg)
                # XML part
                self.__xmlparts[path] = part = cls(path, container)
                container.set_part(path, part.pretty_serialize())
        else:
            for path, part in self.__xmlparts.items():
                if part is not None:
                    container.set_part(path, part.serialize())
        container.save(target, packaging=packaging, backup=backup, pretty=pretty)

    @property
    def content(self) -> Content:
        """Get the content part (content.xml) of the document.

        Returns:
            The `Content` object representing the document's content.

        Raises:
            ValueError: If the content part is empty or cannot be retrieved.

        """
        content: Content | None = self.get_part(ODF_CONTENT)  # ty:ignore
        if content is None:
            msg = "Empty Content"
            raise ValueError(msg)
        return content

    @property
    def styles(self) -> Styles:
        """Get the styles part (styles.xml) of the document.

        Returns:
            The `Styles` object representing the document's styles.

        Raises:
            ValueError: If the styles part is empty or cannot be retrieved.

        """
        styles: Styles | None = self.get_part(ODF_STYLES)  # ty:ignore
        if styles is None:
            msg = "Empty Styles"
            raise ValueError(msg)
        return styles

    # Styles over several parts

    def get_styles(
        self,
        family: str | bytes = "",
        automatic: bool = False,
    ) -> list[StyleBase | DrawFillImage | DrawMarker]:
        """Retrieve a list of styles from both content.xml and styles.xml.

        This method allows filtering styles by family and can include automatic
        styles in the search.

        Args:
            family: The style family to filter by (e.g., 'paragraph', 'text').
                Can be a string or bytes.
            automatic: If `True`, includes automatic styles from styles.xml.

        Returns:
            list[StyleBase | DrawFillImage | DrawMarker]: A list of style-like
                objects matching the criteria.

        """
        # compatibility with old versions:
        if isinstance(family, bytes):
            family = bytes_to_str(family)
        all_styles = self.content.get_styles(family=family) + self.styles.get_styles(
            family=family, automatic=automatic
        )
        return [s for s in all_styles if s is not None]

    def get_style(
        self,
        family: str,
        name_or_element: str | StyleBase | None = None,
        display_name: str | None = None,
    ) -> StyleBase | DrawFillImage | DrawMarker | None:
        """Return the style uniquely identified by its name and family.

        If `name_or_element` is already a `StyleBase` object, it is returned directly.
        If `name_or_element` is `None`, the default style for the given `family` is fetched.
        If `display_name` is provided, it is used to search for styles by their
        user-facing name (as seen in desktop applications), rather than their
        internal `name`.

        Args:
            family: The style family (e.g., 'paragraph', 'text', 'graphic',
                'table', 'list', 'number', 'page-layout', 'master-page').
            name_or_element: The internal name of the style (str), a `StyleBase`
                object itself, or `None` to fetch the default style.
            display_name: The user-facing display name of the style.

        Returns:
            StyleBase | DrawFillImage | DrawMarker | None: The matching style-like,
                instance, or `None` if no matching style is found.

        """
        # 1. content.xml
        element = self.content.get_style(
            family, name_or_element=name_or_element, display_name=display_name
        )
        if element is not None:
            return element
        # 2. styles.xml
        return self.styles.get_style(
            family,
            name_or_element=name_or_element,
            display_name=display_name,
        )

    def get_parent_style(
        self, style: StyleBase
    ) -> StyleBase | DrawFillImage | DrawMarker | None:
        """Get the parent style of a given style.

        Args:
            style: The `StyleBase` object for which to find the parent.

        Returns:
            The parent `StyleBase`, or `None` if the style
            has no parent or the parent style cannot be found.

        """
        if style is None:
            return None
        family = style.family
        if family is None:
            return None
        parent_style_name = style.parent_style
        if not parent_style_name:
            return None
        return self.get_style(family, parent_style_name)

    def get_list_style(self, style: StyleBase) -> StyleBase | None:
        """Get the list style associated with a given style.

        Args:
            style: The `StyleBase` object from which to get the list style name.

        Returns:
            The list `StyleBase` object, or `None` if the style
            has no associated list style or it cannot be found.

        """
        if style is None:
            return None
        list_style_name = getattr(style, "list_style_name", None)
        if not list_style_name:
            return None
        return cast("StyleBase | None", self.get_style("list", list_style_name))

    @staticmethod
    def _pseudo_style_attribute(
        style_element: StyleBase | Element, attribute: str
    ) -> Any:
        if hasattr(style_element, attribute):
            return getattr(style_element, attribute)
        return ""

    def _set_automatic_name(self, style: StyleBase, family: str) -> None:
        """Generate a name for the new automatic style."""
        try:
            name = style.name
        except AttributeError:
            # do nothing
            return
        if not name:
            name = None
        styles = self.get_styles(family=family, automatic=True)
        max_index = 0
        for existing_style in styles:
            if existing_style is None:
                continue
            try:
                existing_name = existing_style.name
            except AttributeError:
                continue
            if not existing_name or not existing_name.startswith(AUTOMATIC_PREFIX):
                continue
            try:
                index = int(existing_name[len(AUTOMATIC_PREFIX) :])
            except ValueError:
                continue
            max_index = max(max_index, index)

        style.name = f"{AUTOMATIC_PREFIX}{max_index + 1}"

    def _insert_style_get_common_styles(
        self,
        family: str,
        name: str,
    ) -> tuple[Any, Any]:
        style_container = self.styles.get_element("office:styles")
        existing = self.styles.get_style(family, name)
        return existing, style_container

    def _insert_style_get_automatic_styles(
        self,
        style: StyleBase,
        family: str,
        name: str,
    ) -> tuple[Any, Any]:
        # fixme: manage forbidden family None (see also v1.4)
        style_container = self.content.get_element("office:automatic-styles")
        # A name ?
        if name:
            with contextlib.suppress(AttributeError):
                style.name = name
            existing = self.content.get_style(family, name)
        else:
            self._set_automatic_name(style, family)
            existing = None
        return existing, style_container

    def _insert_style_get_default_styles(
        self,
        style: StyleBase,
        family: str,
        name: str,
    ) -> tuple[Any, Any]:
        style_container = self.styles.get_element("office:styles")
        style.tag = "style:default-style"
        if name:
            with contextlib.suppress(KeyError):
                style.del_attribute("style:name")
        existing = self.styles.get_style(family)
        return existing, style_container

    def _insert_style_get_master_page(
        self,
        family: str,
        name: str,
    ) -> tuple[Any, Any]:
        style_container = self.styles.get_element("office:master-styles")
        existing = self.styles.get_style(family, name)
        return existing, style_container

    def _insert_style_get_font_face_default(
        self,
        family: str,
        name: str,
    ) -> tuple[Any, Any]:
        style_container = self.styles.get_element("office:font-face-decls")
        existing = self.styles.get_style(family, name)
        return existing, style_container

    def _insert_style_get_font_face(
        self,
        family: str,
        name: str,
    ) -> tuple[Any, Any]:
        style_container = self.content.get_element("office:font-face-decls")
        existing = self.content.get_style(family, name)
        return existing, style_container

    def _insert_style_get_page_layout(
        self,
        family: str,
        name: str,
    ) -> tuple[Any, Any]:
        # force to automatic
        style_container = self.styles.get_element("office:automatic-styles")
        existing = self.styles.get_style(family, name)
        return existing, style_container

    @staticmethod
    def _get_style_element_name(style_element: Element) -> str:
        """Get the internal name or identifier of a style or resource element."""
        if hasattr(style_element, "name") and style_element.name:
            return str(style_element.name)
        for attr in ("style:name", "draw:name", "svg:name", "xml:id"):
            val = style_element.get_attribute(attr)
            if val:
                return str(val)
        return ""

    def _insert_style_get_family_less(
        self,
        style_element: Element,
        name: str,
        automatic: bool,
    ) -> tuple[Element | None, Element]:
        """Get existing element and target container for family-less styles/resources."""
        if automatic:
            style_container = self.styles.get_element(
                "office:automatic-styles"
            ) or self.content.get_element("office:automatic-styles")
        else:
            style_container = self.styles.get_element("office:styles")

        if style_container is None:
            msg = "Target style container not found in document"
            raise ValueError(msg)

        if not name:
            name = self._get_style_element_name(style_element)

        existing = None
        tag = style_element.tag
        if name:
            for attr in ("style:name", "draw:name", "svg:name", "xml:id"):
                element = style_container.get_element(f"{tag}[@{attr}='{name}']")
                if element is not None:
                    existing = element
                    break
        else:
            existing = style_container.get_element(tag)

        return existing, style_container

    def _insert_style_standard(
        self,
        style: StyleBase,
        name: str,
        family: str,
        automatic: bool,
        default: bool,
    ) -> tuple[Any, Any]:
        # Common style
        if name and automatic is False and default is False:
            return self._insert_style_get_common_styles(family, name)
        # Automatic style
        if automatic is True and default is False:
            return self._insert_style_get_automatic_styles(style, family, name)
        # Default style
        if automatic is False and default is True:
            return self._insert_style_get_default_styles(style, family, name)
        msg = "Invalid combination of arguments"
        raise AttributeError(msg)

    def insert_style(
        self,
        style: StyleBase | str,
        name: str = "",
        automatic: bool = False,
        default: bool = False,
    ) -> Any:
        """Insert the given style object into the document.

        The style is inserted according to its family and type (common, automatic,
        or default). If `style` is a string, it's assumed to be an XML style definition.
        If `name` is not provided for a common style, it tries to use the style's
        internal name.

        All styles can't be used as default styles. Default styles are
        allowed for the following families: paragraph, text, section, table,
        table-column, table-row, table-cell, table-page, chart, drawing-page,
        graphic, presentation, control and ruby.

        Args:
            style: The `StyleBase` object to insert, or a string representing an
                XML style definition.
            name: An optional name for the style. If empty, a unique name might be
                generated or the style's inherent name used.
            automatic: If `True`, the style is inserted as an automatic style.
            default: If `True`, the style is inserted as a default style,
                replacing any existing default style of the same family.
                `name` and `display_name` are ignored in this case.

        Returns:
            The name of the inserted style (str).

        Raises:
            TypeError: If the provided `style` is not a `StyleBase` object or a string.
            ValueError: If an invalid style is provided (e.g., unknown family).
            AttributeError: If an invalid combination of `automatic` and `default`
                arguments is provided (they are mutually exclusive).

        """
        # if style is a str, assume it is the Style definition
        if isinstance(style, str):
            style_element: StyleBase = Element.from_tag(style)  # ty: ignore
        else:
            style_element = style
        if not isinstance(style_element, Element):
            msg = f"Unknown Style type: {style!r}"
            raise TypeError(msg)

        # Get family and name
        raw_family = getattr(
            style_element, "family", None
        ) or style_element.get_attribute("style:family")
        family: str | None = str(raw_family) if isinstance(raw_family, str) else None
        if not name:
            name = self._get_style_element_name(style_element)

        # Master page style
        if family == "master-page":
            existing, style_container = self._insert_style_get_master_page(family, name)
        # Font face declarations
        elif family == "font-face":
            if default:
                existing, style_container = self._insert_style_get_font_face_default(
                    family, name
                )
            else:
                existing, style_container = self._insert_style_get_font_face(
                    family, name
                )
        # page layout style
        elif family == "page-layout":
            existing, style_container = self._insert_style_get_page_layout(family, name)
        # Common style with family
        elif family and family in FAMILY_MAPPING:
            existing, style_container = self._insert_style_standard(
                style_element,
                name,
                family,
                automatic,
                default,
            )
        # Elements without a family attribute (draw:marker, draw:gradient, number:*, etc.)
        elif not family or style_element.tag in FAMILY_LESS_STYLE_TAGS:
            existing, style_container = self._insert_style_get_family_less(
                style_element, name, automatic
            )
        # Invalid style
        else:
            msg = (
                "Invalid style: "
                f"{style_element}, tag:{style_element.tag}, family:{family}"
            )
            raise ValueError(msg)

        # Insert it!
        if existing is not None:
            style_container.delete(existing)
        style_container.append(style_element)
        return name or self._get_style_element_name(style_element)

    def get_styled_elements(self, name: str = "") -> list[Element]:
        """Search for elements (paragraphs, tables, etc.) using a given style name.

        This method performs a brute-force search across the document's content
        and style parts.

        Args:
            name: The style name to search for. If empty, all styled elements are returned.

        Returns:
            A list of `Element` objects that are associated with the specified style.

        """
        # Header, footer, etc. have styles too
        return self.content.root.get_styled_elements(
            name
        ) + self.styles.root.get_styled_elements(name)

    def show_styles(
        self,
        automatic: bool = True,
        common: bool = True,
        properties: bool = False,
    ) -> str:
        """Provide a formatted string summary of styles in the document.

        Args:
            automatic: If `True`, include automatic styles in the output.
            common: If `True`, include common (non-automatic) styles.
            properties: If `True`, include the individual properties
                of each style in the output.

        Returns:
            A human-readable summary of the document's styles.

        """
        infos = []
        for style in self.get_styles():
            try:
                name: str = style.name or ""
            except AttributeError:
                print("Style error:")
                print(style.__class__)
                print(style.serialize())
                raise
            if style.__class__.__name__ == "DrawFillImage":
                family = ""
            else:
                family = str(style.family)
            parent = style.parent
            is_auto = parent and parent.tag == "office:automatic-styles"
            if (is_auto and automatic is False) or (not is_auto and common is False):
                continue
            is_used = bool(self.get_styled_elements(name))
            if isinstance(style, StyleBase) and properties:
                style_properties = style.get_properties()
            else:
                style_properties = None
            infos.append(
                {
                    "type": "auto  " if is_auto else "common",
                    "used": "y" if is_used else "n",
                    "family": family,
                    "parent": self._pseudo_style_attribute(style, "parent_style") or "",
                    "name": name or "",
                    "display_name": self._pseudo_style_attribute(style, "display_name")
                    or "",
                    "properties": style_properties,
                }
            )
        if not infos:
            return ""
        # Sort by family and name
        infos.sort(key=itemgetter("family", "name"))
        # Show common and used first
        infos.sort(key=itemgetter("type", "used"), reverse=True)
        max_family = str(max(len(x["family"]) for x in infos))  # ty: ignore
        max_parent = str(max(len(x["parent"]) for x in infos))  # ty: ignore
        formater = (
            "%(type)s used:%(used)s family:%(family)-0"
            + max_family
            + "s parent:%(parent)-0"
            + max_parent
            + "s name:%(name)s"
        )
        output = []
        for info in infos:
            line = formater % info
            if info["display_name"]:
                line += " display_name:" + info["display_name"]  # ty: ignore
            output.append(line)
            if info["properties"]:
                for name, value in info["properties"].items():
                    output.append(f"   - {name}: {value}")
        output.append("")
        return "\n".join(output)

    def delete_styles(self) -> int:
        """Remove all style information from content and all styles.

        First, it removes all references to styles from elements within the
        document. Then, it deletes all supposedly orphaned styles. Default
        styles are not deleted.

        In the ODF standard, a "default" style is explicitly represented by
        the <style:default-style> element (see ODF 1.3 Part 3, Section 3.5).
        These elements provide default formatting properties for an entire
        style family (like paragraphs or tables) when no other style is
        applied.

        Here, these default styles are identified by the fact that they do
        not have a name attribute. While regular common styles or automatic
        styles use the <style:style> element and require a style:name
        attribute, <style:default-style> only has a style:family attribute.

        Returns:
            The number of deleted styles.

        """
        # First remove references to styles
        for element in self.get_styled_elements():
            for attribute in (
                "text:style-name",
                "draw:style-name",
                "draw:text-style-name",
                "table:style-name",
                "style:page-layout-name",
            ):
                with contextlib.suppress(KeyError):
                    element.del_attribute(attribute)
        # Then remove supposedly orphaned styles
        deleted = 0
        for style in self.get_styles():
            try:
                name = style.name or ""
            except AttributeError:
                continue
            # Don't delete default styles or styles without name
            if not name:
                continue
            # elif type(style) is odf_master_page:
            #    # Don't suppress header and footer, just styling was removed
            #    continue
            style.delete()
            deleted += 1
        return deleted

    def _copy_image_from_document(self, document: Document, url: str) -> None:
        """Copy image from another document.

        Args:
            document: The source `Document` object from which to copy image.
            url: url of the image in the source document.

        """
        image_content = document.get_part(url)
        if not isinstance(image_content, bytes):
            return
        self.set_part(url, image_content)
        media_type = document.manifest.get_media_type(url) or "application/octet-stream"
        self.manifest.add_full_path(url, media_type)

    def merge_styles_from(self, document: Document) -> None:
        """Copy all styles from another document into this document.

        Existing styles with the same type and name will be replaced.
        Only unique styles will be preserved. This operation also copies
        any images referenced by master page styles or fill images.

        Args:
            document: The source `Document` object from which to merge styles.

        """
        for style in document.get_styles():
            tagname = style.tag
            family = style.family
            if family is None:
                continue
            stylename = getattr(style, "name", None)
            container = style.parent
            if container is None:
                continue
            upper_container = container.parent
            if upper_container is None:
                continue
            container_name = container.tag
            # The destination part
            if upper_container.tag == "office:document-styles":
                part: Content | Styles = self.styles
            elif upper_container.tag == "office:document-content":
                part = self.content
            else:
                raise NotImplementedError(upper_container.tag)
            # Implemented containers
            if container_name not in {
                "office:styles",
                "office:automatic-styles",
                "office:master-styles",
                "office:font-face-decls",
            }:
                raise NotImplementedError(container_name)
            dest = part.get_element(f"//{container_name}")
            if not dest:
                continue
            # Implemented style types
            # if tagname not in registered_styles:
            #    raise NotImplementedError(tagname)
            duplicate = part.get_style(family, stylename)
            if duplicate is not None:
                duplicate.delete()
            dest.append(style)
            # Copy images from the header/footer
            if tagname == "style:master-page":
                images = cast(
                    "list[DrawImage]", style.get_elements("descendant::draw:image")
                )
                for image in images:
                    self._copy_image_from_document(document, image.url)
            elif tagname == "draw:fill-image":
                draw_fill_image = cast("DrawFillImage", style)
                self._copy_image_from_document(document, draw_fill_image.url)

    def add_page_break_style(self) -> None:
        """Ensure the document contains the style required for a manual page break.

        This method adds or verifies the existence of a paragraph style named
        "odfdopagebreak" with the property `fo:break-after="page"`.
        Once this style is present, a manual page break can be added to the
        document using `document.body.append(PageBreak())`.

        Note: This style uses the property 'fo:break-after'; another
        possibility could be the property 'fo:break-before'.
        """
        if existing := self.get_style(
            family="paragraph",
            name_or_element="odfdopagebreak",
        ):
            properties = existing.get_properties()
            if properties and properties.get("fo:break-after") == "page":
                return
        style = (
            '<style:style style:family="paragraph" style:parent-style-name="Standard" '
            'style:name="odfdopagebreak">'
            '<style:paragraph-properties fo:break-after="page"/></style:style>'
        )
        self.insert_style(style, automatic=False)

    def get_style_properties(
        self, family: str, name: str, area: str | None = None
    ) -> PropDict | None:
        """Return the properties of the required style as a dictionary.

        Args:
            family: The style family (e.g., 'paragraph', 'text').
            name: The name of the style.
            area: An optional string specifying a sub-area of properties (e.g.,
                'paragraph', 'text', 'table-cell').

        Returns:
            A dictionary of style properties (key-value pairs), or `None` if
            the style is not found.

        """
        style = self.get_style(family, name)
        if style is None:
            return None
        return style.get_properties(area=area)

    def _get_table(self, table: int | str | Table) -> Table | None:
        if isinstance(table, Table):
            return table
        if not isinstance(table, (int, str)):
            msg = f"Table parameter must be int or str or Table: {table!r}"
            raise TypeError(msg)
        if isinstance(table, int):
            return self.body.get_table(position=table)
        return self.body.get_table(name=table)

    def get_cell_style_properties(
        self, table: str | int | Table, coord: tuple | list | str
    ) -> PropDict:
        """Return the style properties of a table cell in an ODS document.

        Properties are retrieved from the cell's own style, or from its row's
        style, or from its column's default cell style, in that order of
        precedence.

        Args:
            table: The name (str), index (int), or Table object.
            coord: The coordinates of the cell (e.g., "A1", (0, 0)).

        Returns:
            A dictionary of style properties (key-value pairs) for the cell.
            Returns an empty dictionary if the table or cell is not found,
            or if no styles are applicable.

        """
        if not (sheet := self._get_table(table)):
            return {}
        cell = sheet.get_cell(coord, clone=False)
        if cell.style:
            return (
                self.get_style_properties("table-cell", cell.style, "table-cell") or {}
            )
        with contextlib.suppress(ValueError):
            row = sheet.get_row(cell.y, clone=False, create=False)  # ty: ignore
            if row.style:  # noqa: SIM102
                if props := self.get_style_properties(
                    "table-row", row.style, "table-cell"
                ):
                    return props
            column = sheet.get_column(cell.x)  # ty: ignore
            style = column.default_cell_style
            if style:  # noqa: SIM102
                if props := self.get_style_properties(
                    "table-cell", style, "table-cell"
                ):
                    return props
        return {}

    def get_cell_background_color(
        self,
        table: str | int | Table,
        coord: tuple | list | str,
        default: str = "#ffffff",
    ) -> str:
        """Return the background color of a table cell in an ODS document.

        The color is retrieved from the cell's style properties (cell, row, or column).
        If no background color is explicitly defined, the `default` value is returned.

        Args:
            table: The name (str), index (int), or Table object.
            coord: The coordinates of the cell (e.g., "A1", (0, 0)).
            default: The default color to return if no background color is defined
                (defaults to "#ffffff").

        Returns:
            The background color as a hexadecimal string (e.g., "#RRGGBB").

        """
        found = self.get_cell_style_properties(table, coord).get("fo:background-color")
        return found if isinstance(found, str) else default

    def get_table_style(
        self,
        table: str | int | Table,
    ) -> StyleBase | None:
        """Return the `StyleBase` instance associated with the table.

        Args:
            table: The name (str), index (int), or Table object.

        Returns:
            The `StyleBase` object for the table, or `None` if the table
            is not found or has no style.

        """
        if not (sheet := self._get_table(table)):
            return None
        return self.get_style("table", sheet.style)  # ty: ignore

    def get_table_displayed(self, table: str | int | Table) -> bool:
        """Return the `table:display` property of the table's style.

        This property indicates whether the table should be displayed in a
        graphical interface. This method replaces the broken `Table.displayd()`
        method from previous `odfdo` versions.

        Args:
            table: The name (str), index (int), or Table object.

        Returns:
            `True` if the table is set to be displayed, `False` otherwise.

        """
        style = self.get_table_style(table)
        if not style:
            # should not happen, but assume that a table without style is
            # displayed by default
            return True
        properties = style.get_properties() or {}
        property_str = str(properties.get("table:display", "true"))
        return Boolean.decode(property_str)

    def _unique_style_name(self, base: str) -> str:
        """Generate a unique style name based on a given base string.

        The generated name will be of the form "base_X", where X is an
        incrementing integer that ensures the name is not already in use
        within the document's styles.

        Args:
            base: The base string for generating the unique name.

        Returns:
            A unique style name string.

        """
        current = {style.name for style in self.get_styles() if hasattr(style, "name")}
        idx = 0
        while True:
            name = f"{base}_{idx}"
            if name in current:
                idx += 1
                continue
            return name

    def set_table_displayed(self, table: str | int, displayed: bool) -> None:
        """Set the `table:display` property of the table's style.

        This controls whether the table should be displayed in a graphical
        interface. If the table does not have an existing style, a new
        automatic style is created for it. This method replaces the broken
        `Table.displayd()` method from previous `odfdo` versions.

        Args:
            table: The name (str) or index (int) of the table.
            displayed: A boolean flag; `True` to display the table, `False` to hide it.

        """
        orig_style = self.get_table_style(table)
        if not orig_style:
            name = self._unique_style_name("ta")
            orig_style = Element.from_tag(
                f'<style:style style:name="{name}" style:family="table" '
                'style:master-page-name="Default">'
                '<style:table-properties table:display="true" '
                'style:writing-mode="lr-tb"/></style:style>'
            )
            self.insert_style(orig_style, automatic=True)  # ty:ignore
        new_style = cast("Style", orig_style.clone)
        new_name = self._unique_style_name("ta")
        new_style.name = new_name
        self.insert_style(new_style, automatic=True)
        sheet = self._get_table(table)
        sheet.style = new_name  # ty: ignore
        properties = {"table:display": Boolean.encode(displayed)}
        new_style.set_properties(properties)

    def get_language(self) -> str:
        """Get the default language of the document from its styles.

        Note: The language value in the metadata might differ.

        Returns:
            The default language as a string (e.g., "en-US", "fr-FR").

        """
        return self.styles.default_language

    def set_language(self, language: str) -> None:
        """Set the default language of the document, updating both styles and metadata.

        Args:
            language: The language code as a string (e.g., "en-US", "fr-FR").
                Must conform to RFC 3066.

        Raises:
            TypeError: If the provided language code does not conform to RFC 3066.

        """
        language = str(language)
        if not is_RFC3066(language):
            msg = 'Language must be "xx" lang or "xx-YY" lang-COUNTRY code (RFC3066)'
            raise TypeError(msg)
        self.styles.default_language = language
        self.meta.language = language

    @property
    def language(self) -> str | None:
        """Get or set the default language of the document.

        When getting, it returns the default language as a string (e.g., "en-US"),
        or `None` if not set.

        When setting, it accepts a language code as a string (e.g., "en-US", "fr-FR")
        to update both the styles and metadata of the document.

        Returns:
            The default language as a string (e.g., "en-US"), or `None` if not set.

        """
        return self.get_language()

    @language.setter
    def language(self, language: str) -> None:
        return self.set_language(language)

__body instance-attribute

__body: Element | None = None

__xmlparts instance-attribute

__xmlparts: dict[str, XmlPart] = {}

body property

body: Body

Get the body element of the content part.

The body element is where the actual content of the ODF document (e.g., paragraphs, tables, images) is stored.

Returns:

Type Description
Body

The Body element of the document’s content part.

Raises:

Type Description
ValueError

If the content part is missing or the body element cannot be retrieved.

clone property

clone: Document

Return an exact, deep copy of the document.

All internal structures, including the container and its parts, are duplicated.

Returns:

Type Description
Document

A new Document instance that is a deep copy of the original.

Raises:

Type Description
ValueError

If the original document’s container is empty.

container instance-attribute

container: Container | None = None

content property

content: Content

Get the content part (content.xml) of the document.

Returns:

Type Description
Content

The Content object representing the document’s content.

Raises:

Type Description
ValueError

If the content part is empty or cannot be retrieved.

language property writable

language: str | None

Get or set the default language of the document.

When getting, it returns the default language as a string (e.g., “en-US”), or None if not set.

When setting, it accepts a language code as a string (e.g., “en-US”, “fr-FR”) to update both the styles and metadata of the document.

Returns:

Type Description
str | None

The default language as a string (e.g., “en-US”), or None if not set.

manifest property

manifest: Manifest

Get the manifest part (manifest.xml) of the document.

The manifest lists all files within the ODF package and their MIME types.

Returns:

Type Description
Manifest

The Manifest object representing the document’s manifest.

Raises:

Type Description
ValueError

If the manifest part is empty or cannot be retrieved as a Manifest object.

meta property

meta: Meta

Get the meta part (meta.xml) of the document.

The meta part stores metadata about the document, such as author, creation date, and modification date.

Returns:

Type Description
Meta

The Meta object representing the document’s metadata.

Raises:

Type Description
ValueError

If the metadata part is empty or cannot be retrieved as a Meta object.

mimetype property writable

mimetype: str

Get or set the MIME type of the document.

When getting, it returns the MIME type as a string (e.g., “application/vnd.oasis.opendocument.text”).

When setting, it accepts a new MIME type as a string.

Returns:

Type Description
str

The MIME type as a string.

Raises:

Type Description
ValueError

If the document’s container is empty.

parts property

parts: list[str]

Get the names of all available parts within the document’s archive.

The paths are relative to the archive root, e.g., ‘content.xml’, ‘Pictures/100000000000032000000258912EB1C3.jpg’.

This is a convenience property that calls get_parts().

Returns:

Type Description
list[str]

A list of strings, where each string is the path of a part.

path property writable

path: Path | None

Get or set the path of the document’s container.

When getting, it returns the Path object of the container, or None if the container is not set.

When setting, it accepts a string or Path object to update the container’s path.

Returns:

Type Description
Path | None

The Path object of the container, or None if the container is not set.

settings property

settings: Settings

Get the settings part (settings.xml) of the document.

The settings part stores document-wide configuration and preferences.

Returns:

Name Type Description
Settings Settings

The Settings object representing the document’s settings.

Raises:

Type Description
ValueError

If the settings part is empty or cannot be retrieved.

styles property

styles: Styles

Get the styles part (styles.xml) of the document.

Returns:

Type Description
Styles

The Styles object representing the document’s styles.

Raises:

Type Description
ValueError

If the styles part is empty or cannot be retrieved.

__init__

__init__(
    target: str
    | bytes
    | Path
    | Container
    | BytesIO
    | None = "text",
) -> None

Initialize a Document.

This can either create a new document from a template or load an existing one from a path, file-like object, or Container.

Parameters:

Name Type Description Default
target str | bytes | Path | Container | BytesIO | None

The source to create or load the document from. - If a string like “text”, “spreadsheet”, “presentation”, “drawing”, or their file extensions (“odt”, “ods”, “odp”, “odg”), a new document is created from a default template. Note: These templates are not truly empty and may require clearing (e.g., document.body.clear()). - If a path (str or Path) to an existing ODF file, the file is loaded. - If a Container object, it is used directly. - If a file-like object (io.BytesIO), the document is loaded from it. - If None, an empty container is created. - If bytes, the content is loaded as a string.

'text'

To create a document from a custom template, use the Document.new() classmethod instead.

When creating an “empty” document: the document is a copy of the default templates document provided with this library, which, as templates, are not really empty. It may be useful to clear the newly created document: document.body.clear(), or adjust meta information like description or language: document.language = 'fr-FR'.

Source code in odfdo/document.py
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
def __init__(
    self,
    target: str | bytes | Path | Container | io.BytesIO | None = "text",
) -> None:
    """Initialize a Document.

    This can either create a new document from a template or load an
    existing one from a path, file-like object, or Container.

    Args:
        target:
            The source to create or load the document from.
            - If a string like "text", "spreadsheet", "presentation",
              "drawing", or their file extensions ("odt", "ods", "odp",
              "odg"), a new document is created from a default template.
              Note: These templates are not truly empty and may require
              clearing (e.g., `document.body.clear()`).
            - If a path (str or Path) to an existing ODF file, the file
              is loaded.
            - If a `Container` object, it is used directly.
            - If a file-like object (`io.BytesIO`), the document is loaded
              from it.
            - If `None`, an empty container is created.
            - If `bytes`, the content is loaded as a string.

    To create a document from a custom template, use the `Document.new()`
    classmethod instead.

    When creating an “empty” document: the document is a copy of the
    default templates document provided with this library, which, as
    templates, are not really empty. It may be useful to clear the newly
    created document: `document.body.clear()`, or adjust meta information
    like description or language: `document.language = 'fr-FR'`.

    """
    # Cache of XML parts
    self.__xmlparts: dict[str, XmlPart] = {}
    # Cache of the body
    self.__body: Element | None = None
    self.container: Container | None = None
    if isinstance(target, bytes):
        # eager conversion
        target = bytes_to_str(target)
    if target is None:
        # empty document, you probably don't want this.
        self.container = Container()
        return
    if isinstance(target, Path):
        # let's assume we open a container on existing file
        self.container = Container(target)
        return
    if isinstance(target, Container):
        # special internal case, use an existing container
        self.container = target
        return
    if isinstance(target, str):
        if target in ODF_TEMPLATES:
            # assuming a new document from templates
            self.container = _container_from_template(target)
            return
        # let's assume we open a container on existing file
        self.container = Container(target)
        return
    if isinstance(target, io.BytesIO):
        self.container = Container(target)
        return
    msg = f"Unknown Document source type: {target!r}"
    raise TypeError(msg)

__repr__

__repr__() -> str
Source code in odfdo/document.py
337
338
def __repr__(self) -> str:
    return f"<{self.__class__.__name__} type={self.get_type()} path={self.path}>"

__str__

__str__() -> str
Source code in odfdo/document.py
340
341
342
343
344
def __str__(self) -> str:
    try:
        return str(self.get_formatted_text())
    except NotImplementedError:
        return str(self.body)

_add_binary_part

_add_binary_part(blob: Blob) -> str
Source code in odfdo/document.py
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
def _add_binary_part(self, blob: Blob) -> str:
    if not self.container:
        msg = "Empty Container"
        raise ValueError(msg)
    manifest = self.manifest
    if manifest.get_media_type("Pictures/") is None:
        manifest.add_full_path("Pictures/")
    path = posixpath.join("Pictures", blob.name)
    self.container.set_part(path, blob.content)
    manifest.add_full_path(path, blob.mime_type)
    return path

_check_manifest_rdf

_check_manifest_rdf() -> None
Source code in odfdo/document.py
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
def _check_manifest_rdf(self) -> None:
    if not self.container:
        return
    manifest = self.manifest
    parts = self.container.parts
    if manifest.get_media_type(ODF_MANIFEST_RDF):
        if ODF_MANIFEST_RDF not in parts:
            self.container.set_part(
                ODF_MANIFEST_RDF, self.container.default_manifest_rdf.encode("utf8")
            )
    else:
        if ODF_MANIFEST_RDF in parts:
            self.container.del_part(ODF_MANIFEST_RDF)

_copy_image_from_document

_copy_image_from_document(
    document: Document, url: str
) -> None

Copy image from another document.

Parameters:

Name Type Description Default
document Document

The source Document object from which to copy image.

required
url str

url of the image in the source document.

required
Source code in odfdo/document.py
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
def _copy_image_from_document(self, document: Document, url: str) -> None:
    """Copy image from another document.

    Args:
        document: The source `Document` object from which to copy image.
        url: url of the image in the source document.

    """
    image_content = document.get_part(url)
    if not isinstance(image_content, bytes):
        return
    self.set_part(url, image_content)
    media_type = document.manifest.get_media_type(url) or "application/octet-stream"
    self.manifest.add_full_path(url, media_type)

_ensure_odf14

_ensure_odf14() -> None

Upgrade older ODF documents to ODF 1.4 and create missing core parts.

Existing XML parts get their office:version attribute set to “1.4”. Missing core parts (content.xml, styles.xml, meta.xml, settings.xml) are copied from the default template for the document type and added to the manifest.

Note

The ODF 1.4 specification keeps the same namespace URIs as earlier versions for the core vocabularies, so only the office:version attribute needs to change; missing extension namespace declarations are added implicitly when those prefixes are actually used.

Source code in odfdo/document.py
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
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
def _ensure_odf14(self) -> None:
    """Upgrade older ODF documents to ODF 1.4 and create missing core
    parts.

    Existing XML parts get their `office:version` attribute set to "1.4".
    Missing core parts (`content.xml`, `styles.xml`, `meta.xml`,
    `settings.xml`) are copied from the default template for the document
    type and added to the manifest.

    Note:
        The ODF 1.4 specification keeps the same namespace URIs as earlier
        versions for the core vocabularies, so only the `office:version`
        attribute needs to change; missing extension namespace declarations
        are added implicitly when those prefixes are actually used.

    """
    if not self.container:
        return
    if ODF_CONTENT not in self.container.parts:
        # Too broken to fix automatically.
        return
    content_part = self.get_part(ODF_CONTENT)
    if content_part is None or not isinstance(content_part, XmlPart):
        return
    current_version = content_part.root.get_attribute("office:version")
    all_parts_present = all(
        path in self.container.parts
        for path in (ODF_META, ODF_SETTINGS, ODF_STYLES)
    )
    if current_version == OFFICE_VERSION and all_parts_present:
        return

    doc_type = self.get_type()
    template_container = _template_container(doc_type)
    manifest = self.get_part(ODF_MANIFEST)
    if not isinstance(manifest, Manifest):
        return
    for path in (ODF_CONTENT, ODF_META, ODF_SETTINGS, ODF_STYLES):
        part = self.__xmlparts.get(path)
        if part is None and path not in self.container.parts:
            if template_container is None:
                continue
            raw_data = template_container.get_part(path)
            if raw_data is None:
                continue
            template_data = (
                raw_data.encode("utf-8") if isinstance(raw_data, str) else raw_data
            )
            self.container.set_part(path, template_data)
            manifest.add_full_path(path, "text/xml")
            part = self.get_part(path)
        elif part is None:
            part = self.get_part(path)
        if part is not None and isinstance(part, XmlPart):
            part.root.set_attribute("office:version", OFFICE_VERSION)
    # Keep manifest:version in sync with office:version. LibreOffice is
    # strict about this attribute and may report a corrupt document when
    # office:version is "1.4" but manifest:version is still "1.3".
    manifest.root.set_attribute("manifest:version", OFFICE_VERSION)
    root_entry = manifest.root.get_element(
        "//manifest:file-entry[@manifest:full-path='/']"
    )
    if root_entry is not None:
        root_entry.set_attribute("manifest:version", OFFICE_VERSION)
    self.container.set_part(ODF_MANIFEST, manifest.serialize())

_formatted_text

_formatted_text(rst_mode: bool) -> str
Source code in odfdo/document.py
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
def _formatted_text(self, rst_mode: bool) -> str:
    # Initialize an empty context
    context = {
        "document": self,
        "footnotes": [],
        "endnotes": [],
        "annotations": [],
        "rst_mode": rst_mode,
        "img_counter": 0,
        "images": [],
        "no_img_level": 0,
    }
    body = self.body
    # Get the text
    result = []
    for child in body.children:
        # self._get_formatted_text_child(result, element, context, rst_mode)
        # if child.tag == "table:table":
        #     result.append(child.get_formatted_text(context))
        #     return
        result.append(child.get_formatted_text(context))
        if context["footnotes"]:
            self._get_formatted_text_footnotes(result, context, rst_mode)
        if context["annotations"]:
            self._get_formatted_text_annotations(result, context, rst_mode)
        # Insert the images ref, only in rst mode
        if context["images"]:
            self._get_formatted_text_images(result, context, rst_mode)
    if context["endnotes"]:
        self._get_formatted_text_endnotes(result, context, rst_mode)
    return "".join(result)

_get_formatted_text_annotations

_get_formatted_text_annotations(
    result: list[str], context: dict, rst_mode: bool
) -> None
Source code in odfdo/document.py
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
def _get_formatted_text_annotations(
    self,
    result: list[str],
    context: dict,
    rst_mode: bool,
) -> None:
    # Insert the annotations
    # With a separation
    if rst_mode:
        result.append("\n")
    else:
        result.append("----\n")
    for annotation in context["annotations"]:
        if rst_mode:
            result.append(f".. [#] {annotation}\n")
        else:
            result.append(f"[*] {annotation}\n")
    context["annotations"] = []

_get_formatted_text_endnotes

_get_formatted_text_endnotes(
    result: list[str], context: dict, rst_mode: bool
) -> None
Source code in odfdo/document.py
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
def _get_formatted_text_endnotes(
    self,
    result: list[str],
    context: dict,
    rst_mode: bool,
) -> None:
    # Append the end notes
    if rst_mode:
        result.append("\n\n")
    else:
        result.append("\n========\n")
    for citation, body in context["endnotes"]:
        if rst_mode:
            result.append(f".. [*] {body}\n")
        else:
            result.append(f"({citation}) {body}\n")

_get_formatted_text_footnotes

_get_formatted_text_footnotes(
    result: list[str], context: dict, rst_mode: bool
) -> None
Source code in odfdo/document.py
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
def _get_formatted_text_footnotes(
    self,
    result: list[str],
    context: dict,
    rst_mode: bool,
) -> None:
    # Separate text from notes
    if rst_mode:
        result.append("\n")
    else:
        result.append("----\n")
    for citation, body in context["footnotes"]:
        if rst_mode:
            result.append(f".. [#] {body}\n")
        else:
            result.append(f"[{citation}] {body}\n")
    # Append a \n after the notes
    result.append("\n")
    # Reset for the next paragraph
    context["footnotes"] = []

_get_formatted_text_images

_get_formatted_text_images(
    result: list[str], context: dict, rst_mode: bool
) -> None
Source code in odfdo/document.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
def _get_formatted_text_images(
    self,
    result: list[str],
    context: dict,
    rst_mode: bool,
) -> None:
    # Insert the images ref, only in rst mode
    result.append("\n")
    for ref, filename, (width, height) in context["images"]:
        result.append(f".. {ref} image:: {filename}\n")
        if width is not None:
            result.append(f"   :width: {width}\n")
        if height is not None:
            result.append(f"   :height: {height}\n")
    context["images"] = []

_get_style_element_name staticmethod

_get_style_element_name(style_element: Element) -> str

Get the internal name or identifier of a style or resource element.

Source code in odfdo/document.py
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
@staticmethod
def _get_style_element_name(style_element: Element) -> str:
    """Get the internal name or identifier of a style or resource element."""
    if hasattr(style_element, "name") and style_element.name:
        return str(style_element.name)
    for attr in ("style:name", "draw:name", "svg:name", "xml:id"):
        val = style_element.get_attribute(attr)
        if val:
            return str(val)
    return ""

_get_table

_get_table(table: int | str | Table) -> Table | None
Source code in odfdo/document.py
2169
2170
2171
2172
2173
2174
2175
2176
2177
def _get_table(self, table: int | str | Table) -> Table | None:
    if isinstance(table, Table):
        return table
    if not isinstance(table, (int, str)):
        msg = f"Table parameter must be int or str or Table: {table!r}"
        raise TypeError(msg)
    if isinstance(table, int):
        return self.body.get_table(position=table)
    return self.body.get_table(name=table)

_insert_style_get_automatic_styles

_insert_style_get_automatic_styles(
    style: StyleBase, family: str, name: str
) -> tuple[Any, Any]
Source code in odfdo/document.py
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
def _insert_style_get_automatic_styles(
    self,
    style: StyleBase,
    family: str,
    name: str,
) -> tuple[Any, Any]:
    # fixme: manage forbidden family None (see also v1.4)
    style_container = self.content.get_element("office:automatic-styles")
    # A name ?
    if name:
        with contextlib.suppress(AttributeError):
            style.name = name
        existing = self.content.get_style(family, name)
    else:
        self._set_automatic_name(style, family)
        existing = None
    return existing, style_container

_insert_style_get_common_styles

_insert_style_get_common_styles(
    family: str, name: str
) -> tuple[Any, Any]
Source code in odfdo/document.py
1658
1659
1660
1661
1662
1663
1664
1665
def _insert_style_get_common_styles(
    self,
    family: str,
    name: str,
) -> tuple[Any, Any]:
    style_container = self.styles.get_element("office:styles")
    existing = self.styles.get_style(family, name)
    return existing, style_container

_insert_style_get_default_styles

_insert_style_get_default_styles(
    style: StyleBase, family: str, name: str
) -> tuple[Any, Any]
Source code in odfdo/document.py
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
def _insert_style_get_default_styles(
    self,
    style: StyleBase,
    family: str,
    name: str,
) -> tuple[Any, Any]:
    style_container = self.styles.get_element("office:styles")
    style.tag = "style:default-style"
    if name:
        with contextlib.suppress(KeyError):
            style.del_attribute("style:name")
    existing = self.styles.get_style(family)
    return existing, style_container

_insert_style_get_family_less

_insert_style_get_family_less(
    style_element: Element, name: str, automatic: bool
) -> tuple[Element | None, Element]

Get existing element and target container for family-less styles/resources.

Source code in odfdo/document.py
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
def _insert_style_get_family_less(
    self,
    style_element: Element,
    name: str,
    automatic: bool,
) -> tuple[Element | None, Element]:
    """Get existing element and target container for family-less styles/resources."""
    if automatic:
        style_container = self.styles.get_element(
            "office:automatic-styles"
        ) or self.content.get_element("office:automatic-styles")
    else:
        style_container = self.styles.get_element("office:styles")

    if style_container is None:
        msg = "Target style container not found in document"
        raise ValueError(msg)

    if not name:
        name = self._get_style_element_name(style_element)

    existing = None
    tag = style_element.tag
    if name:
        for attr in ("style:name", "draw:name", "svg:name", "xml:id"):
            element = style_container.get_element(f"{tag}[@{attr}='{name}']")
            if element is not None:
                existing = element
                break
    else:
        existing = style_container.get_element(tag)

    return existing, style_container

_insert_style_get_font_face

_insert_style_get_font_face(
    family: str, name: str
) -> tuple[Any, Any]
Source code in odfdo/document.py
1717
1718
1719
1720
1721
1722
1723
1724
def _insert_style_get_font_face(
    self,
    family: str,
    name: str,
) -> tuple[Any, Any]:
    style_container = self.content.get_element("office:font-face-decls")
    existing = self.content.get_style(family, name)
    return existing, style_container

_insert_style_get_font_face_default

_insert_style_get_font_face_default(
    family: str, name: str
) -> tuple[Any, Any]
Source code in odfdo/document.py
1708
1709
1710
1711
1712
1713
1714
1715
def _insert_style_get_font_face_default(
    self,
    family: str,
    name: str,
) -> tuple[Any, Any]:
    style_container = self.styles.get_element("office:font-face-decls")
    existing = self.styles.get_style(family, name)
    return existing, style_container

_insert_style_get_master_page

_insert_style_get_master_page(
    family: str, name: str
) -> tuple[Any, Any]
Source code in odfdo/document.py
1699
1700
1701
1702
1703
1704
1705
1706
def _insert_style_get_master_page(
    self,
    family: str,
    name: str,
) -> tuple[Any, Any]:
    style_container = self.styles.get_element("office:master-styles")
    existing = self.styles.get_style(family, name)
    return existing, style_container

_insert_style_get_page_layout

_insert_style_get_page_layout(
    family: str, name: str
) -> tuple[Any, Any]
Source code in odfdo/document.py
1726
1727
1728
1729
1730
1731
1732
1733
1734
def _insert_style_get_page_layout(
    self,
    family: str,
    name: str,
) -> tuple[Any, Any]:
    # force to automatic
    style_container = self.styles.get_element("office:automatic-styles")
    existing = self.styles.get_style(family, name)
    return existing, style_container

_insert_style_standard

_insert_style_standard(
    style: StyleBase,
    name: str,
    family: str,
    automatic: bool,
    default: bool,
) -> tuple[Any, Any]
Source code in odfdo/document.py
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
def _insert_style_standard(
    self,
    style: StyleBase,
    name: str,
    family: str,
    automatic: bool,
    default: bool,
) -> tuple[Any, Any]:
    # Common style
    if name and automatic is False and default is False:
        return self._insert_style_get_common_styles(family, name)
    # Automatic style
    if automatic is True and default is False:
        return self._insert_style_get_automatic_styles(style, family, name)
    # Default style
    if automatic is False and default is True:
        return self._insert_style_get_default_styles(style, family, name)
    msg = "Invalid combination of arguments"
    raise AttributeError(msg)

_markdown_export_tables

_markdown_export_tables() -> list[TableMarkdown]
Source code in odfdo/document.py
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
def _markdown_export_tables(self) -> list[TableMarkdown]:
    doc_stem = self.path.stem if self.path else "spreadsheet"
    doc_stem = doc_stem.replace(" ", "_")
    tables = self.body.tables
    unifyer = NameUnifyer()
    results: list[TableMarkdown] = []
    _set_global(self)
    try:
        for table in tables:
            raw_table_name = table.name or ""
            table_name = raw_table_name.replace(" ", "_")
            unique_name = unifyer.unique(table_name)
            identifier = f"{doc_stem}#{unique_name}"
            content = table.to_markdown()
            results.append(TableMarkdown(identifier, content))
    finally:
        _set_global(None)
    return results

_pseudo_style_attribute staticmethod

_pseudo_style_attribute(
    style_element: StyleBase | Element, attribute: str
) -> Any
Source code in odfdo/document.py
1622
1623
1624
1625
1626
1627
1628
@staticmethod
def _pseudo_style_attribute(
    style_element: StyleBase | Element, attribute: str
) -> Any:
    if hasattr(style_element, attribute):
        return getattr(style_element, attribute)
    return ""

_set_automatic_name

_set_automatic_name(style: StyleBase, family: str) -> None

Generate a name for the new automatic style.

Source code in odfdo/document.py
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
def _set_automatic_name(self, style: StyleBase, family: str) -> None:
    """Generate a name for the new automatic style."""
    try:
        name = style.name
    except AttributeError:
        # do nothing
        return
    if not name:
        name = None
    styles = self.get_styles(family=family, automatic=True)
    max_index = 0
    for existing_style in styles:
        if existing_style is None:
            continue
        try:
            existing_name = existing_style.name
        except AttributeError:
            continue
        if not existing_name or not existing_name.startswith(AUTOMATIC_PREFIX):
            continue
        try:
            index = int(existing_name[len(AUTOMATIC_PREFIX) :])
        except ValueError:
            continue
        max_index = max(max_index, index)

    style.name = f"{AUTOMATIC_PREFIX}{max_index + 1}"

_tables_csv

_tables_csv() -> str
Source code in odfdo/document.py
735
736
def _tables_csv(self) -> str:
    return "\n\n".join(str(table) for table in self.body.tables)

_unique_style_name

_unique_style_name(base: str) -> str

Generate a unique style name based on a given base string.

The generated name will be of the form “base_X”, where X is an incrementing integer that ensures the name is not already in use within the document’s styles.

Parameters:

Name Type Description Default
base str

The base string for generating the unique name.

required

Returns:

Type Description
str

A unique style name string.

Source code in odfdo/document.py
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
def _unique_style_name(self, base: str) -> str:
    """Generate a unique style name based on a given base string.

    The generated name will be of the form "base_X", where X is an
    incrementing integer that ensures the name is not already in use
    within the document's styles.

    Args:
        base: The base string for generating the unique name.

    Returns:
        A unique style name string.

    """
    current = {style.name for style in self.get_styles() if hasattr(style, "name")}
    idx = 0
    while True:
        name = f"{base}_{idx}"
        if name in current:
            idx += 1
            continue
        return name

add_file

add_file(path_or_file: str | Path | BinaryIO) -> str

Insert a file from a path or a file-like object into the document’s container.

The internal name of the file in the “Pictures/” folder is generated by a hash function. The method returns the full path (URI) that can be used to reference the added file within the document’s content.

Parameters:

Name Type Description Default
path_or_file str | Path | BinaryIO

The path to the file (str or Path) or a file-like object (BinaryIO) containing the file’s content.

required

Returns:

Type Description
str

The full path (URI) to reference the added file in the content.

Raises:

Type Description
ValueError

If the document’s container is empty.

Source code in odfdo/document.py
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
def add_file(self, path_or_file: str | Path | BinaryIO) -> str:
    """Insert a file from a path or a file-like object into the document's container.

    The internal name of the file in the "Pictures/" folder is generated
    by a hash function. The method returns the full path (URI) that can be
    used to reference the added file within the document's content.

    Args:
        path_or_file: The path to the file (str or Path) or a file-like
            object (`BinaryIO`) containing the file's content.

    Returns:
        The full path (URI) to reference the added file in the content.

    Raises:
        ValueError: If the document's container is empty.

    """
    if not self.container:
        msg = "Empty Container"
        raise ValueError(msg)
    if isinstance(path_or_file, (str, Path)):
        blob = Blob.from_path(path_or_file)
    else:
        blob = Blob.from_io(path_or_file)
    return self._add_binary_part(blob)

add_page_break_style

add_page_break_style() -> None

Ensure the document contains the style required for a manual page break.

This method adds or verifies the existence of a paragraph style named “odfdopagebreak” with the property fo:break-after="page". Once this style is present, a manual page break can be added to the document using document.body.append(PageBreak()).

Note: This style uses the property ‘fo:break-after’; another possibility could be the property ‘fo:break-before’.

Source code in odfdo/document.py
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
def add_page_break_style(self) -> None:
    """Ensure the document contains the style required for a manual page break.

    This method adds or verifies the existence of a paragraph style named
    "odfdopagebreak" with the property `fo:break-after="page"`.
    Once this style is present, a manual page break can be added to the
    document using `document.body.append(PageBreak())`.

    Note: This style uses the property 'fo:break-after'; another
    possibility could be the property 'fo:break-before'.
    """
    if existing := self.get_style(
        family="paragraph",
        name_or_element="odfdopagebreak",
    ):
        properties = existing.get_properties()
        if properties and properties.get("fo:break-after") == "page":
            return
    style = (
        '<style:style style:family="paragraph" style:parent-style-name="Standard" '
        'style:name="odfdopagebreak">'
        '<style:paragraph-properties fo:break-after="page"/></style:style>'
    )
    self.insert_style(style, automatic=False)

del_part

del_part(path: str) -> None

Mark a part for deletion from the document’s archive.

This method marks a specified part for deletion from the ODF document. The actual deletion occurs when the document is saved.

Parameters:

Name Type Description Default
path str

The path of the part relative to the archive, e.g., “Pictures/1003200258912EB1C3.jpg”. Shortcuts like “content” are also supported.

required

Raises:

Type Description
ValueError

If the document’s container is empty, or if an attempt is made to delete a mandatory part (e.g., “manifest.xml”).

Source code in odfdo/document.py
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
def del_part(self, path: str) -> None:
    """Mark a part for deletion from the document's archive.

    This method marks a specified part for deletion from the ODF document.
    The actual deletion occurs when the document is saved.

    Args:
        path: The path of the part relative to the archive, e.g.,
            "Pictures/1003200258912EB1C3.jpg". Shortcuts like "content"
            are also supported.

    Raises:
        ValueError: If the document's container is empty, or if an attempt
            is made to delete a mandatory part (e.g., "manifest.xml").

    """
    if not self.container:
        msg = "Empty Container"
        raise ValueError(msg)
    path = _get_part_path(path)
    cls = _get_part_class(path)
    if path == ODF_MANIFEST or cls is not None:
        msg = f"part '{path}' is mandatory"
        raise ValueError(msg)
    self.container.del_part(path)

delete_styles

delete_styles() -> int

Remove all style information from content and all styles.

First, it removes all references to styles from elements within the document. Then, it deletes all supposedly orphaned styles. Default styles are not deleted.

In the ODF standard, a “default” style is explicitly represented by the element (see ODF 1.3 Part 3, Section 3.5). These elements provide default formatting properties for an entire style family (like paragraphs or tables) when no other style is applied.

Here, these default styles are identified by the fact that they do not have a name attribute. While regular common styles or automatic styles use the element and require a style:name attribute, only has a style:family attribute.

Returns:

Type Description
int

The number of deleted styles.

Source code in odfdo/document.py
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
def delete_styles(self) -> int:
    """Remove all style information from content and all styles.

    First, it removes all references to styles from elements within the
    document. Then, it deletes all supposedly orphaned styles. Default
    styles are not deleted.

    In the ODF standard, a "default" style is explicitly represented by
    the <style:default-style> element (see ODF 1.3 Part 3, Section 3.5).
    These elements provide default formatting properties for an entire
    style family (like paragraphs or tables) when no other style is
    applied.

    Here, these default styles are identified by the fact that they do
    not have a name attribute. While regular common styles or automatic
    styles use the <style:style> element and require a style:name
    attribute, <style:default-style> only has a style:family attribute.

    Returns:
        The number of deleted styles.

    """
    # First remove references to styles
    for element in self.get_styled_elements():
        for attribute in (
            "text:style-name",
            "draw:style-name",
            "draw:text-style-name",
            "table:style-name",
            "style:page-layout-name",
        ):
            with contextlib.suppress(KeyError):
                element.del_attribute(attribute)
    # Then remove supposedly orphaned styles
    deleted = 0
    for style in self.get_styles():
        try:
            name = style.name or ""
        except AttributeError:
            continue
        # Don't delete default styles or styles without name
        if not name:
            continue
        # elif type(style) is odf_master_page:
        #    # Don't suppress header and footer, just styling was removed
        #    continue
        style.delete()
        deleted += 1
    return deleted

from_dict classmethod

from_dict(
    data: dict[str, Any] | list[dict[str, Any]],
    table_name: str | None = None,
    guess_type: bool = False,
    language: str | None = None,
) -> Document

Create a new spreadsheet Document from dictionary data.

Accepts: - Multi-sheet dict: {"Sheet1": data1, "Sheet2": data2} - Single table data (dict of columns, list of record dicts, or matrix)

Parameters:

Name Type Description Default
data dict[str, Any] | list[dict[str, Any]]

The dictionary or list of dicts to import.

required
table_name str | None

Optional name for single-table import.

None
guess_type bool

If True, try to detect Python type from strings values (int, float, dates).

False
language str | None

Optional document language code.

None
Example

Multi-sheet: columnar format

data = { … “product”: { … “reference”: [“ref01”, “ref02”], … “price”: [10, 20.5], … }, … “stock”: { … “reference”: [“ref01”, “ref02”], … “qty”: [100, 50], … }, … } doc = Document.from_dict(data)

Multi-sheet: records format

data = { … “product”: [ … {“reference”: “ref01”, “price”: 10}, … {“reference”: “ref02”, “price”: 20.5}, … ], … “stock”: [ … {“reference”: “ref01”, “qty”: 100}, … {“reference”: “ref02”, “qty”: 50}, … ], … } doc = Document.from_dict(data)

Multi-sheet: matrix format

data = { … “product”: [ … [“reference”, “price”], … [“ref01”, 10], … [“ref02”, 20.5], … ], … “stock”: [ … [“reference”, “qty”], … [“ref01”, 100], … [“ref02”, 50], … ], … } doc = Document.from_dict(data)

Single table: columnar dict

data = { … “reference”: [“ref01”, “ref02”], … “price”: [10, 20.5], … } doc = Document.from_dict(data, table_name=”product”)

Single table: list of records

data = [ … {“reference”: “ref01”, “price”: 10}, … {“reference”: “ref02”, “price”: 20.5}, … ] doc = Document.from_dict(data, table_name=”product”)

Returns:

Name Type Description
Document Document

A new spreadsheet Document populated with the tables.

Raises:

Type Description
TypeError

If data is not a dict or list of dicts.

Source code in odfdo/document.py
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
@classmethod
def from_dict(
    cls,
    data: dict[str, Any] | list[dict[str, Any]],
    table_name: str | None = None,
    guess_type: bool = False,
    language: str | None = None,
) -> Document:
    """Create a new spreadsheet Document from dictionary data.

    Accepts:
    - Multi-sheet dict: `{"Sheet1": data1, "Sheet2": data2}`
    - Single table data (dict of columns, list of record dicts, or matrix)

    Args:
        data: The dictionary or list of dicts to import.
        table_name: Optional name for single-table import.
        guess_type: If True, try to detect Python type from strings
            values (int, float, dates).
        language: Optional document language code.

    Example:
        # Multi-sheet: columnar format
        >>> data = {
        ...     "product": {
        ...         "reference": ["ref01", "ref02"],
        ...         "price": [10, 20.5],
        ...     },
        ...     "stock": {
        ...         "reference": ["ref01", "ref02"],
        ...         "qty": [100, 50],
        ...     },
        ... }
        >>> doc = Document.from_dict(data)

        # Multi-sheet: records format
        >>> data = {
        ...     "product": [
        ...         {"reference": "ref01", "price": 10},
        ...         {"reference": "ref02", "price": 20.5},
        ...     ],
        ...     "stock": [
        ...         {"reference": "ref01", "qty": 100},
        ...         {"reference": "ref02", "qty": 50},
        ...     ],
        ... }
        >>> doc = Document.from_dict(data)

        # Multi-sheet: matrix format
        >>> data = {
        ...     "product": [
        ...         ["reference", "price"],
        ...         ["ref01", 10],
        ...         ["ref02", 20.5],
        ...     ],
        ...     "stock": [
        ...         ["reference", "qty"],
        ...         ["ref01", 100],
        ...         ["ref02", 50],
        ...     ],
        ... }
        >>> doc = Document.from_dict(data)

        # Single table: columnar dict
        >>> data = {
        ...     "reference": ["ref01", "ref02"],
        ...     "price": [10, 20.5],
        ... }
        >>> doc = Document.from_dict(data, table_name="product")

        # Single table: list of records
        >>> data = [
        ...     {"reference": "ref01", "price": 10},
        ...     {"reference": "ref02", "price": 20.5},
        ... ]
        >>> doc = Document.from_dict(data, table_name="product")

    Returns:
        Document: A new spreadsheet Document populated with the tables.

    Raises:
        TypeError: If data is not a dict or list of dicts.

    """
    doc = cls.new("spreadsheet")
    doc.body.clear()
    unifyer = NameUnifyer()

    if isinstance(data, dict):
        if not data:
            name = unifyer.unique(table_name or "")
            doc.body.append(Table.from_dict({}, name=name))
        else:
            first_val = next(iter(data.values()))
            if isinstance(first_val, dict) or (
                isinstance(first_val, list)
                and (
                    (
                        len(data) > 1
                        and (
                            not first_val or isinstance(first_val[0], (dict, list))
                        )
                    )
                    or (
                        len(data) == 1
                        and bool(first_val)
                        and isinstance(first_val[0], dict)
                    )
                )
            ):
                for name, sheet_data in data.items():
                    unique_name = unifyer.unique(name or "")
                    if isinstance(sheet_data, list) and (
                        not sheet_data or isinstance(sheet_data[0], list)
                    ):
                        table = Table.from_dict(
                            {unique_name: sheet_data},
                            name=unique_name,
                            guess_type=guess_type,
                        )
                    else:
                        table = Table.from_dict(
                            sheet_data,
                            name=unique_name,
                            guess_type=guess_type,
                        )
                    doc.body.append(table)
            else:
                # Single table (columnar dict or single matrix)
                if (
                    len(data) == 1
                    and isinstance(first_val, list)
                    and (not first_val or isinstance(first_val[0], list))
                ):
                    name = table_name
                else:
                    name = unifyer.unique(table_name or "")
                table = Table.from_dict(
                    data,
                    name=name,
                    guess_type=guess_type,
                )
                doc.body.append(table)
    elif isinstance(data, list):
        name = unifyer.unique(table_name or "")
        table = Table.from_dict(
            data,
            name=name,
            guess_type=guess_type,
        )
        doc.body.append(table)
    else:
        msg = "Data must be a dict or list of dicts"
        raise TypeError(msg)

    if language:
        doc.language = language

    return doc

from_json classmethod

from_json(
    content: str | Path | dict[str, list[list[Any]]],
    table_name: str = "",
) -> Document

Create a new spreadsheet Document from JSON content.

Parameters:

Name Type Description Default
content str | Path | dict[str, list[list[Any]]]

A JSON string, a Path or filename to a JSON file, or a dictionary mapping table names to 2D lists of cell values.

required
table_name str

Name of the table if the input is a list.

''

Returns:

Name Type Description
Document Document

A new spreadsheet Document containing Table elements for each table in the JSON content.

Raises:

Type Description
TypeError

If content is not a string, Path, or dict, or if the decoded JSON structure is not a dictionary.

Source code in odfdo/document.py
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
@classmethod
def from_json(
    cls,
    content: str | Path | dict[str, list[list[Any]]],
    table_name: str = "",
) -> Document:
    """Create a new spreadsheet Document from JSON content.

    Args:
        content: A JSON string, a Path or filename to a JSON file, or a
            dictionary mapping table names to 2D lists of cell values.
        table_name: Name of the table if the input is a list.

    Returns:
        Document: A new spreadsheet Document containing Table elements
            for each table in the JSON content.

    Raises:
        TypeError: If content is not a string, Path, or dict, or if the
            decoded JSON structure is not a dictionary.

    """
    data: Any
    if isinstance(content, Path):
        data = json.loads(content.read_text(encoding="utf-8"))
    elif isinstance(content, str):
        with contextlib.suppress(OSError, ValueError):
            if Path(content).is_file():
                content = Path(content).read_text(encoding="utf-8")
        data = json.loads(content)
    elif isinstance(content, dict | list):
        data = content
    else:
        msg = "JSON content must be a string, Path, dict or list"
        raise TypeError(msg)

    if not isinstance(data, dict | list):
        msg = (
            "JSON document content must be a dictionary mapping "
            "table names to row lists or a list of rows"
        )
        raise TypeError(msg)

    doc = cls.new("spreadsheet")
    body = doc.body
    body.clear()

    if isinstance(data, dict):
        for t_name, rows in data.items():
            table = Table(t_name)
            table.clear()
            body.append(table)
            _populate_table(table, rows)
    else:  # list
        unifyer = NameUnifyer()
        name = unifyer.unique(table_name)
        table = Table(name)
        table.clear()
        body.append(table)
        _populate_table(table, data)

    return doc

get_cell_background_color

get_cell_background_color(
    table: str | int | Table,
    coord: tuple | list | str,
    default: str = "#ffffff",
) -> str

Return the background color of a table cell in an ODS document.

The color is retrieved from the cell’s style properties (cell, row, or column). If no background color is explicitly defined, the default value is returned.

Parameters:

Name Type Description Default
table str | int | Table

The name (str), index (int), or Table object.

required
coord tuple | list | str

The coordinates of the cell (e.g., “A1”, (0, 0)).

required
default str

The default color to return if no background color is defined (defaults to “#ffffff”).

'#ffffff'

Returns:

Type Description
str

The background color as a hexadecimal string (e.g., “#RRGGBB”).

Source code in odfdo/document.py
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
def get_cell_background_color(
    self,
    table: str | int | Table,
    coord: tuple | list | str,
    default: str = "#ffffff",
) -> str:
    """Return the background color of a table cell in an ODS document.

    The color is retrieved from the cell's style properties (cell, row, or column).
    If no background color is explicitly defined, the `default` value is returned.

    Args:
        table: The name (str), index (int), or Table object.
        coord: The coordinates of the cell (e.g., "A1", (0, 0)).
        default: The default color to return if no background color is defined
            (defaults to "#ffffff").

    Returns:
        The background color as a hexadecimal string (e.g., "#RRGGBB").

    """
    found = self.get_cell_style_properties(table, coord).get("fo:background-color")
    return found if isinstance(found, str) else default

get_cell_style_properties

get_cell_style_properties(
    table: str | int | Table, coord: tuple | list | str
) -> PropDict

Return the style properties of a table cell in an ODS document.

Properties are retrieved from the cell’s own style, or from its row’s style, or from its column’s default cell style, in that order of precedence.

Parameters:

Name Type Description Default
table str | int | Table

The name (str), index (int), or Table object.

required
coord tuple | list | str

The coordinates of the cell (e.g., “A1”, (0, 0)).

required

Returns:

Type Description
PropDict

A dictionary of style properties (key-value pairs) for the cell.

PropDict

Returns an empty dictionary if the table or cell is not found,

PropDict

or if no styles are applicable.

Source code in odfdo/document.py
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
def get_cell_style_properties(
    self, table: str | int | Table, coord: tuple | list | str
) -> PropDict:
    """Return the style properties of a table cell in an ODS document.

    Properties are retrieved from the cell's own style, or from its row's
    style, or from its column's default cell style, in that order of
    precedence.

    Args:
        table: The name (str), index (int), or Table object.
        coord: The coordinates of the cell (e.g., "A1", (0, 0)).

    Returns:
        A dictionary of style properties (key-value pairs) for the cell.
        Returns an empty dictionary if the table or cell is not found,
        or if no styles are applicable.

    """
    if not (sheet := self._get_table(table)):
        return {}
    cell = sheet.get_cell(coord, clone=False)
    if cell.style:
        return (
            self.get_style_properties("table-cell", cell.style, "table-cell") or {}
        )
    with contextlib.suppress(ValueError):
        row = sheet.get_row(cell.y, clone=False, create=False)  # ty: ignore
        if row.style:  # noqa: SIM102
            if props := self.get_style_properties(
                "table-row", row.style, "table-cell"
            ):
                return props
        column = sheet.get_column(cell.x)  # ty: ignore
        style = column.default_cell_style
        if style:  # noqa: SIM102
            if props := self.get_style_properties(
                "table-cell", style, "table-cell"
            ):
                return props
    return {}

get_formated_meta

get_formated_meta() -> str

Return meta information as text, with some formatting.

(Redirection to new implementation for compatibility.)

Returns:

Type Description
str

A formatted string containing the document’s metadata.

Source code in odfdo/document.py
770
771
772
773
774
775
776
777
778
779
def get_formated_meta(self) -> str:
    """Return meta information as text, with some formatting.

    (Redirection to new implementation for compatibility.)

    Returns:
        A formatted string containing the document's metadata.

    """
    return self.meta.as_text()

get_formatted_text

get_formatted_text(rst_mode: bool = False) -> str

Return a formatted string representation of the document’s content.

For text-based documents, this includes handling of footnotes, annotations, and image references. For spreadsheets, it returns a CSV representation.

Parameters:

Name Type Description Default
rst_mode bool

If True, formats the output in reStructuredText (RST) syntax, especially for footnotes and annotations.

False

Returns:

Name Type Description
str str

The formatted text content of the document.

Raises:

Type Description
NotImplementedError

If the document type is not supported for formatted text extraction.

Source code in odfdo/document.py
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
def get_formatted_text(self, rst_mode: bool = False) -> str:
    """Return a formatted string representation of the document's content.

    For text-based documents, this includes handling of footnotes, annotations,
    and image references. For spreadsheets, it returns a CSV representation.

    Args:
        rst_mode: If True, formats the output in reStructuredText (RST)
            syntax, especially for footnotes and annotations.

    Returns:
        str: The formatted text content of the document.

    Raises:
        NotImplementedError: If the document type is not supported for
            formatted text extraction.

    """
    # For the moment, only "type='text'"
    doc_type = self.get_type()
    if doc_type == "spreadsheet":
        return self._tables_csv()
    if doc_type in {
        "text",
        "text-template",
        "presentation",
        "presentation-template",
    }:
        return self._formatted_text(rst_mode)
    msg = f"Type of document {doc_type!r} not supported yet"
    raise NotImplementedError(msg)

get_language

get_language() -> str

Get the default language of the document from its styles.

Note: The language value in the metadata might differ.

Returns:

Type Description
str

The default language as a string (e.g., “en-US”, “fr-FR”).

Source code in odfdo/document.py
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
def get_language(self) -> str:
    """Get the default language of the document from its styles.

    Note: The language value in the metadata might differ.

    Returns:
        The default language as a string (e.g., "en-US", "fr-FR").

    """
    return self.styles.default_language

get_list_style

get_list_style(style: StyleBase) -> StyleBase | None

Get the list style associated with a given style.

Parameters:

Name Type Description Default
style StyleBase

The StyleBase object from which to get the list style name.

required

Returns:

Type Description
StyleBase | None

The list StyleBase object, or None if the style

StyleBase | None

has no associated list style or it cannot be found.

Source code in odfdo/document.py
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
def get_list_style(self, style: StyleBase) -> StyleBase | None:
    """Get the list style associated with a given style.

    Args:
        style: The `StyleBase` object from which to get the list style name.

    Returns:
        The list `StyleBase` object, or `None` if the style
        has no associated list style or it cannot be found.

    """
    if style is None:
        return None
    list_style_name = getattr(style, "list_style_name", None)
    if not list_style_name:
        return None
    return cast("StyleBase | None", self.get_style("list", list_style_name))

get_parent_style

get_parent_style(
    style: StyleBase,
) -> StyleBase | DrawFillImage | DrawMarker | None

Get the parent style of a given style.

Parameters:

Name Type Description Default
style StyleBase

The StyleBase object for which to find the parent.

required

Returns:

Type Description
StyleBase | DrawFillImage | DrawMarker | None

The parent StyleBase, or None if the style

StyleBase | DrawFillImage | DrawMarker | None

has no parent or the parent style cannot be found.

Source code in odfdo/document.py
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
def get_parent_style(
    self, style: StyleBase
) -> StyleBase | DrawFillImage | DrawMarker | None:
    """Get the parent style of a given style.

    Args:
        style: The `StyleBase` object for which to find the parent.

    Returns:
        The parent `StyleBase`, or `None` if the style
        has no parent or the parent style cannot be found.

    """
    if style is None:
        return None
    family = style.family
    if family is None:
        return None
    parent_style_name = style.parent_style
    if not parent_style_name:
        return None
    return self.get_style(family, parent_style_name)

get_part

get_part(path: str) -> XmlPart | str | bytes | None

Return the bytes of the given part. The path is relative to the archive, e.g. “Pictures/1003200258912EB1C3.jpg”.

‘content’, ‘meta’, ‘settings’, ‘styles’ and ‘manifest’ are shortcuts to the real path, e.g. content.xml, and return a dedicated object with its own API.

The path parameter is formatted as URI, so always use ‘/’ separator.

Parameters:

Name Type Description Default
path str

relative path or one of ‘content’, ‘meta’, ‘settings’, ‘styles’ or ‘manifest’.

required

Returns:

Type Description
XmlPart | str | bytes | None

XmlPart | str | bytes | None: the part content.

Source code in odfdo/document.py
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
def get_part(self, path: str) -> XmlPart | str | bytes | None:
    """Return the bytes of the given part. The path is relative to the
    archive, e.g. "Pictures/1003200258912EB1C3.jpg".

    'content', 'meta', 'settings', 'styles' and 'manifest' are shortcuts to
    the real path, e.g. content.xml, and return a dedicated object with its
    own API.

    The path parameter is formatted as URI, so always use '/' separator.

    Args:
        path: relative path or one of 'content', 'meta', 'settings',
            'styles' or 'manifest'.

    Returns:
         XmlPart | str | bytes | None: the part content.

    """
    if not self.container:
        msg = "Empty Container"
        raise ValueError(msg)
    # "./ObjectReplacements/Object 1"
    path = path.lstrip("./")
    path = _get_part_path(path)
    cls = _get_part_class(path)
    # Raw bytes
    if cls is None:
        return self.container.get_part(path)
    # XML part
    part = self.__xmlparts.get(path)
    if part is None:
        self.__xmlparts[path] = part = cls(path, self.container)
    return part

get_parts

get_parts() -> list[str]

Get the names of all available parts within the document’s archive.

This is a helper method for the parts property.

Returns:

Type Description
list[str]

A list of strings, where each string is the path of a part.

Raises:

Type Description
ValueError

If the document’s container is empty.

Source code in odfdo/document.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
def get_parts(self) -> list[str]:
    """Get the names of all available parts within the document's archive.

    This is a helper method for the `parts` property.

    Returns:
        A list of strings, where each string is the path of a part.

    Raises:
        ValueError: If the document's container is empty.

    """
    if not self.container:
        msg = "Empty Container"
        raise ValueError(msg)
    return self.container.parts

get_style

get_style(
    family: str,
    name_or_element: str | StyleBase | None = None,
    display_name: str | None = None,
) -> StyleBase | DrawFillImage | DrawMarker | None

Return the style uniquely identified by its name and family.

If name_or_element is already a StyleBase object, it is returned directly. If name_or_element is None, the default style for the given family is fetched. If display_name is provided, it is used to search for styles by their user-facing name (as seen in desktop applications), rather than their internal name.

Parameters:

Name Type Description Default
family str

The style family (e.g., ‘paragraph’, ‘text’, ‘graphic’, ‘table’, ‘list’, ‘number’, ‘page-layout’, ‘master-page’).

required
name_or_element str | StyleBase | None

The internal name of the style (str), a StyleBase object itself, or None to fetch the default style.

None
display_name str | None

The user-facing display name of the style.

None

Returns:

Type Description
StyleBase | DrawFillImage | DrawMarker | None

StyleBase | DrawFillImage | DrawMarker | None: The matching style-like, instance, or None if no matching style is found.

Source code in odfdo/document.py
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
def get_style(
    self,
    family: str,
    name_or_element: str | StyleBase | None = None,
    display_name: str | None = None,
) -> StyleBase | DrawFillImage | DrawMarker | None:
    """Return the style uniquely identified by its name and family.

    If `name_or_element` is already a `StyleBase` object, it is returned directly.
    If `name_or_element` is `None`, the default style for the given `family` is fetched.
    If `display_name` is provided, it is used to search for styles by their
    user-facing name (as seen in desktop applications), rather than their
    internal `name`.

    Args:
        family: The style family (e.g., 'paragraph', 'text', 'graphic',
            'table', 'list', 'number', 'page-layout', 'master-page').
        name_or_element: The internal name of the style (str), a `StyleBase`
            object itself, or `None` to fetch the default style.
        display_name: The user-facing display name of the style.

    Returns:
        StyleBase | DrawFillImage | DrawMarker | None: The matching style-like,
            instance, or `None` if no matching style is found.

    """
    # 1. content.xml
    element = self.content.get_style(
        family, name_or_element=name_or_element, display_name=display_name
    )
    if element is not None:
        return element
    # 2. styles.xml
    return self.styles.get_style(
        family,
        name_or_element=name_or_element,
        display_name=display_name,
    )

get_style_properties

get_style_properties(
    family: str, name: str, area: str | None = None
) -> PropDict | None

Return the properties of the required style as a dictionary.

Parameters:

Name Type Description Default
family str

The style family (e.g., ‘paragraph’, ‘text’).

required
name str

The name of the style.

required
area str | None

An optional string specifying a sub-area of properties (e.g., ‘paragraph’, ‘text’, ‘table-cell’).

None

Returns:

Type Description
PropDict | None

A dictionary of style properties (key-value pairs), or None if

PropDict | None

the style is not found.

Source code in odfdo/document.py
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
def get_style_properties(
    self, family: str, name: str, area: str | None = None
) -> PropDict | None:
    """Return the properties of the required style as a dictionary.

    Args:
        family: The style family (e.g., 'paragraph', 'text').
        name: The name of the style.
        area: An optional string specifying a sub-area of properties (e.g.,
            'paragraph', 'text', 'table-cell').

    Returns:
        A dictionary of style properties (key-value pairs), or `None` if
        the style is not found.

    """
    style = self.get_style(family, name)
    if style is None:
        return None
    return style.get_properties(area=area)

get_styled_elements

get_styled_elements(name: str = '') -> list[Element]

Search for elements (paragraphs, tables, etc.) using a given style name.

This method performs a brute-force search across the document’s content and style parts.

Parameters:

Name Type Description Default
name str

The style name to search for. If empty, all styled elements are returned.

''

Returns:

Type Description
list[Element]

A list of Element objects that are associated with the specified style.

Source code in odfdo/document.py
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
def get_styled_elements(self, name: str = "") -> list[Element]:
    """Search for elements (paragraphs, tables, etc.) using a given style name.

    This method performs a brute-force search across the document's content
    and style parts.

    Args:
        name: The style name to search for. If empty, all styled elements are returned.

    Returns:
        A list of `Element` objects that are associated with the specified style.

    """
    # Header, footer, etc. have styles too
    return self.content.root.get_styled_elements(
        name
    ) + self.styles.root.get_styled_elements(name)

get_styles

get_styles(
    family: str | bytes = "", automatic: bool = False
) -> list[StyleBase | DrawFillImage | DrawMarker]

Retrieve a list of styles from both content.xml and styles.xml.

This method allows filtering styles by family and can include automatic styles in the search.

Parameters:

Name Type Description Default
family str | bytes

The style family to filter by (e.g., ‘paragraph’, ‘text’). Can be a string or bytes.

''
automatic bool

If True, includes automatic styles from styles.xml.

False

Returns:

Type Description
list[StyleBase | DrawFillImage | DrawMarker]

list[StyleBase | DrawFillImage | DrawMarker]: A list of style-like objects matching the criteria.

Source code in odfdo/document.py
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
def get_styles(
    self,
    family: str | bytes = "",
    automatic: bool = False,
) -> list[StyleBase | DrawFillImage | DrawMarker]:
    """Retrieve a list of styles from both content.xml and styles.xml.

    This method allows filtering styles by family and can include automatic
    styles in the search.

    Args:
        family: The style family to filter by (e.g., 'paragraph', 'text').
            Can be a string or bytes.
        automatic: If `True`, includes automatic styles from styles.xml.

    Returns:
        list[StyleBase | DrawFillImage | DrawMarker]: A list of style-like
            objects matching the criteria.

    """
    # compatibility with old versions:
    if isinstance(family, bytes):
        family = bytes_to_str(family)
    all_styles = self.content.get_styles(family=family) + self.styles.get_styles(
        family=family, automatic=automatic
    )
    return [s for s in all_styles if s is not None]

get_table_displayed

get_table_displayed(table: str | int | Table) -> bool

Return the table:display property of the table’s style.

This property indicates whether the table should be displayed in a graphical interface. This method replaces the broken Table.displayd() method from previous odfdo versions.

Parameters:

Name Type Description Default
table str | int | Table

The name (str), index (int), or Table object.

required

Returns:

Type Description
bool

True if the table is set to be displayed, False otherwise.

Source code in odfdo/document.py
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
def get_table_displayed(self, table: str | int | Table) -> bool:
    """Return the `table:display` property of the table's style.

    This property indicates whether the table should be displayed in a
    graphical interface. This method replaces the broken `Table.displayd()`
    method from previous `odfdo` versions.

    Args:
        table: The name (str), index (int), or Table object.

    Returns:
        `True` if the table is set to be displayed, `False` otherwise.

    """
    style = self.get_table_style(table)
    if not style:
        # should not happen, but assume that a table without style is
        # displayed by default
        return True
    properties = style.get_properties() or {}
    property_str = str(properties.get("table:display", "true"))
    return Boolean.decode(property_str)

get_table_style

get_table_style(
    table: str | int | Table,
) -> StyleBase | None

Return the StyleBase instance associated with the table.

Parameters:

Name Type Description Default
table str | int | Table

The name (str), index (int), or Table object.

required

Returns:

Type Description
StyleBase | None

The StyleBase object for the table, or None if the table

StyleBase | None

is not found or has no style.

Source code in odfdo/document.py
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
def get_table_style(
    self,
    table: str | int | Table,
) -> StyleBase | None:
    """Return the `StyleBase` instance associated with the table.

    Args:
        table: The name (str), index (int), or Table object.

    Returns:
        The `StyleBase` object for the table, or `None` if the table
        is not found or has no style.

    """
    if not (sheet := self._get_table(table)):
        return None
    return self.get_style("table", sheet.style)  # ty: ignore

get_type

get_type() -> str

Get the ODF type (also called class) of this document.

'chart', 'database', 'formula', 'graphics',

Type Description
str

‘graphics-template’, ‘image’, ‘presentation’,

str

‘presentation-template’, ‘spreadsheet’, ‘spreadsheet-template’,

str

‘text’, ‘text-master’, ‘text-template’ or ‘text-web’

Source code in odfdo/document.py
540
541
542
543
544
545
546
547
548
549
550
551
552
def get_type(self) -> str:
    """Get the ODF type (also called class) of this document.

    Returns: 'chart', 'database', 'formula', 'graphics',
        'graphics-template', 'image', 'presentation',
        'presentation-template', 'spreadsheet', 'spreadsheet-template',
        'text', 'text-master', 'text-template' or 'text-web'
    """
    # The mimetype must be with the form:
    # application/vnd.oasis.opendocument.text

    # Isolate and return the last part
    return self.mimetype.rsplit(".", 1)[-1]

insert_style

insert_style(
    style: StyleBase | str,
    name: str = "",
    automatic: bool = False,
    default: bool = False,
) -> Any

Insert the given style object into the document.

The style is inserted according to its family and type (common, automatic, or default). If style is a string, it’s assumed to be an XML style definition. If name is not provided for a common style, it tries to use the style’s internal name.

All styles can’t be used as default styles. Default styles are allowed for the following families: paragraph, text, section, table, table-column, table-row, table-cell, table-page, chart, drawing-page, graphic, presentation, control and ruby.

Parameters:

Name Type Description Default
style StyleBase | str

The StyleBase object to insert, or a string representing an XML style definition.

required
name str

An optional name for the style. If empty, a unique name might be generated or the style’s inherent name used.

''
automatic bool

If True, the style is inserted as an automatic style.

False
default bool

If True, the style is inserted as a default style, replacing any existing default style of the same family. name and display_name are ignored in this case.

False

Returns:

Type Description
Any

The name of the inserted style (str).

Raises:

Type Description
TypeError

If the provided style is not a StyleBase object or a string.

ValueError

If an invalid style is provided (e.g., unknown family).

AttributeError

If an invalid combination of automatic and default arguments is provided (they are mutually exclusive).

Source code in odfdo/document.py
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
def insert_style(
    self,
    style: StyleBase | str,
    name: str = "",
    automatic: bool = False,
    default: bool = False,
) -> Any:
    """Insert the given style object into the document.

    The style is inserted according to its family and type (common, automatic,
    or default). If `style` is a string, it's assumed to be an XML style definition.
    If `name` is not provided for a common style, it tries to use the style's
    internal name.

    All styles can't be used as default styles. Default styles are
    allowed for the following families: paragraph, text, section, table,
    table-column, table-row, table-cell, table-page, chart, drawing-page,
    graphic, presentation, control and ruby.

    Args:
        style: The `StyleBase` object to insert, or a string representing an
            XML style definition.
        name: An optional name for the style. If empty, a unique name might be
            generated or the style's inherent name used.
        automatic: If `True`, the style is inserted as an automatic style.
        default: If `True`, the style is inserted as a default style,
            replacing any existing default style of the same family.
            `name` and `display_name` are ignored in this case.

    Returns:
        The name of the inserted style (str).

    Raises:
        TypeError: If the provided `style` is not a `StyleBase` object or a string.
        ValueError: If an invalid style is provided (e.g., unknown family).
        AttributeError: If an invalid combination of `automatic` and `default`
            arguments is provided (they are mutually exclusive).

    """
    # if style is a str, assume it is the Style definition
    if isinstance(style, str):
        style_element: StyleBase = Element.from_tag(style)  # ty: ignore
    else:
        style_element = style
    if not isinstance(style_element, Element):
        msg = f"Unknown Style type: {style!r}"
        raise TypeError(msg)

    # Get family and name
    raw_family = getattr(
        style_element, "family", None
    ) or style_element.get_attribute("style:family")
    family: str | None = str(raw_family) if isinstance(raw_family, str) else None
    if not name:
        name = self._get_style_element_name(style_element)

    # Master page style
    if family == "master-page":
        existing, style_container = self._insert_style_get_master_page(family, name)
    # Font face declarations
    elif family == "font-face":
        if default:
            existing, style_container = self._insert_style_get_font_face_default(
                family, name
            )
        else:
            existing, style_container = self._insert_style_get_font_face(
                family, name
            )
    # page layout style
    elif family == "page-layout":
        existing, style_container = self._insert_style_get_page_layout(family, name)
    # Common style with family
    elif family and family in FAMILY_MAPPING:
        existing, style_container = self._insert_style_standard(
            style_element,
            name,
            family,
            automatic,
            default,
        )
    # Elements without a family attribute (draw:marker, draw:gradient, number:*, etc.)
    elif not family or style_element.tag in FAMILY_LESS_STYLE_TAGS:
        existing, style_container = self._insert_style_get_family_less(
            style_element, name, automatic
        )
    # Invalid style
    else:
        msg = (
            "Invalid style: "
            f"{style_element}, tag:{style_element.tag}, family:{family}"
        )
        raise ValueError(msg)

    # Insert it!
    if existing is not None:
        style_container.delete(existing)
    style_container.append(style_element)
    return name or self._get_style_element_name(style_element)

merge_styles_from

merge_styles_from(document: Document) -> None

Copy all styles from another document into this document.

Existing styles with the same type and name will be replaced. Only unique styles will be preserved. This operation also copies any images referenced by master page styles or fill images.

Parameters:

Name Type Description Default
document Document

The source Document object from which to merge styles.

required
Source code in odfdo/document.py
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
def merge_styles_from(self, document: Document) -> None:
    """Copy all styles from another document into this document.

    Existing styles with the same type and name will be replaced.
    Only unique styles will be preserved. This operation also copies
    any images referenced by master page styles or fill images.

    Args:
        document: The source `Document` object from which to merge styles.

    """
    for style in document.get_styles():
        tagname = style.tag
        family = style.family
        if family is None:
            continue
        stylename = getattr(style, "name", None)
        container = style.parent
        if container is None:
            continue
        upper_container = container.parent
        if upper_container is None:
            continue
        container_name = container.tag
        # The destination part
        if upper_container.tag == "office:document-styles":
            part: Content | Styles = self.styles
        elif upper_container.tag == "office:document-content":
            part = self.content
        else:
            raise NotImplementedError(upper_container.tag)
        # Implemented containers
        if container_name not in {
            "office:styles",
            "office:automatic-styles",
            "office:master-styles",
            "office:font-face-decls",
        }:
            raise NotImplementedError(container_name)
        dest = part.get_element(f"//{container_name}")
        if not dest:
            continue
        # Implemented style types
        # if tagname not in registered_styles:
        #    raise NotImplementedError(tagname)
        duplicate = part.get_style(family, stylename)
        if duplicate is not None:
            duplicate.delete()
        dest.append(style)
        # Copy images from the header/footer
        if tagname == "style:master-page":
            images = cast(
                "list[DrawImage]", style.get_elements("descendant::draw:image")
            )
            for image in images:
                self._copy_image_from_document(document, image.url)
        elif tagname == "draw:fill-image":
            draw_fill_image = cast("DrawFillImage", style)
            self._copy_image_from_document(document, draw_fill_image.url)

new classmethod

new(template: str | Path | BytesIO = 'text') -> Document

Create a new Document from a template.

Parameters:

Name Type Description Default
template str | Path | BytesIO

The template to use. - If a string like “text”, “spreadsheet”, etc., a default template is used. - If a path to a custom template file, that template is used. - If a file-like object, the template is read from it.

'text'

Returns:

Name Type Description
Document Document

A new Document instance based on the template.

Source code in odfdo/document.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
@classmethod
def new(cls, template: str | Path | io.BytesIO = "text") -> Document:
    """Create a new Document from a template.

    Args:
        template: The template to use.
            - If a string like "text", "spreadsheet", etc., a default
              template is used.
            - If a path to a custom template file, that template is used.
            - If a file-like object, the template is read from it.

    Returns:
        Document: A new Document instance based on the template.

    """
    container = _container_from_template(template)
    return cls(container)

normalize_tables

normalize_tables() -> None

Ensure all tables in the document have table:table-column definitions covering the full width of their rows.

Source code in odfdo/document.py
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
def normalize_tables(self) -> None:
    """Ensure all tables in the document have table:table-column
    definitions covering the full width of their rows.
    """
    if not self.container:
        return
    tables: list[Table] = []
    with contextlib.suppress(ValueError, AttributeError, TypeError):
        tables.extend(self.body.get_tables())
    styles = self.get_part(ODF_STYLES)
    if isinstance(styles, XmlPart):
        tables.extend(
            elem
            for elem in styles.get_elements("//table:table")
            if isinstance(elem, Table)
        )
    for table in tables:
        table.normalize_columns()

save

save(
    target: str | Path | BytesIO | None = None,
    packaging: str = ZIP,
    pretty: bool | None = None,
    backup: bool = False,
) -> None

Save the document to a target path or file-like object.

The document can be saved at its original location, or to a new path or file-like object. It can be saved as a Zip file (default), flat XML format, or as files in a folder (for debugging purposes). XML parts can be pretty printed.

Note: ‘xml’ packaging is an experimental work in progress.

Parameters:

Name Type Description Default
target str | Path | BytesIO | None

The destination to save the document to. Can be a string path, a Path object, or a file-like object (io.BytesIO). If None, the document is saved to its original path.

None
packaging str

The packaging format: ‘zip’ (default), ‘folder’, or ‘xml’.

ZIP
pretty bool | None

If True, XML parts will be pretty-printed. If None (default), it defaults to True for ‘folder’ and ‘xml’ packaging.

None
backup bool

If True, a backup of the existing file will be created before saving.

False

Raises:

Type Description
ValueError

If the document’s container is empty or an unsupported packaging type is specified.

RuntimeError

In unexpected scenarios during XML part handling.

Source code in odfdo/document.py
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
def save(
    self,
    target: str | Path | io.BytesIO | None = None,
    packaging: str = ZIP,
    pretty: bool | None = None,
    backup: bool = False,
) -> None:
    """Save the document to a target path or file-like object.

    The document can be saved at its original location, or to a new path
    or file-like object. It can be saved as a Zip file (default),
    flat XML format, or as files in a folder (for debugging purposes).
    XML parts can be pretty printed.

    Note: 'xml' packaging is an experimental work in progress.

    Args:
        target: The destination to save the document to. Can be a string
            path, a `Path` object, or a file-like object (`io.BytesIO`).
            If `None`, the document is saved to its original path.
        packaging: The packaging format: 'zip' (default), 'folder', or 'xml'.
        pretty: If `True`, XML parts will be pretty-printed. If `None` (default),
            it defaults to `True` for 'folder' and 'xml' packaging.
        backup: If `True`, a backup of the existing file will be created
            before saving.

    Raises:
        ValueError: If the document's container is empty or an unsupported
            packaging type is specified.
        RuntimeError: In unexpected scenarios during XML part handling.

    """
    if not self.container:
        msg = "Empty Container"
        raise ValueError(msg)
    if packaging not in PACKAGING:
        msg = f"Packaging of type {packaging!r} is not supported"
        raise ValueError(msg)
    if target is None and self.path is None:
        msg = "Saving a document without path requires a target"
        raise ValueError(msg)
    # Some advertising
    if packaging != FOLDER:
        self.meta.set_generator_default()
    # Synchronize data with container
    container = self.container
    if pretty is None:
        pretty = packaging in {"folder", "xml"}
    pretty = bool(pretty)
    backup = bool(backup)
    # Folder packaging is intended for debugging/analysis: preserve the
    # original parts (version, missing files, manifest.rdf, table columns)
    # as much as possible, but still pretty-print XML when requested.
    if packaging != FOLDER:
        self._ensure_odf14()
        self._check_manifest_rdf()
        self.normalize_tables()
    if pretty and packaging != XML:
        for path, part in self.__xmlparts.items():
            if part is not None:
                container.set_part(path, part.pretty_serialize())
        for path in (ODF_CONTENT, ODF_META, ODF_SETTINGS, ODF_STYLES):
            if path in self.__xmlparts:
                continue
            # Only create and serialize the part if it exists in the container
            if path not in container.parts:
                continue
            cls = _get_part_class(path)
            if cls is None:
                msg = "Should never happen"
                raise RuntimeError(msg)
            # XML part
            self.__xmlparts[path] = part = cls(path, container)
            container.set_part(path, part.pretty_serialize())
    else:
        for path, part in self.__xmlparts.items():
            if part is not None:
                container.set_part(path, part.serialize())
    container.save(target, packaging=packaging, backup=backup, pretty=pretty)

set_language

set_language(language: str) -> None

Set the default language of the document, updating both styles and metadata.

Parameters:

Name Type Description Default
language str

The language code as a string (e.g., “en-US”, “fr-FR”). Must conform to RFC 3066.

required

Raises:

Type Description
TypeError

If the provided language code does not conform to RFC 3066.

Source code in odfdo/document.py
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
def set_language(self, language: str) -> None:
    """Set the default language of the document, updating both styles and metadata.

    Args:
        language: The language code as a string (e.g., "en-US", "fr-FR").
            Must conform to RFC 3066.

    Raises:
        TypeError: If the provided language code does not conform to RFC 3066.

    """
    language = str(language)
    if not is_RFC3066(language):
        msg = 'Language must be "xx" lang or "xx-YY" lang-COUNTRY code (RFC3066)'
        raise TypeError(msg)
    self.styles.default_language = language
    self.meta.language = language

set_part

set_part(path: str, data: bytes) -> None

Set the bytes of a given part within the document’s archive.

This method updates the content of an existing part or adds a new part to the document.

Parameters:

Name Type Description Default
path str

The path of the part relative to the archive, e.g., “Pictures/image.jpg”. Shortcuts like “content”, “meta”, “settings”, “styles”, and “manifest” are also supported. The path should use ‘/’ as a separator.

required
data bytes

The bytes object containing the content to set for the part.

required

Raises:

Type Description
ValueError

If the document’s container is empty.

Source code in odfdo/document.py
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
def set_part(self, path: str, data: bytes) -> None:
    """Set the bytes of a given part within the document's archive.

    This method updates the content of an existing part or adds a new part
    to the document.

    Args:
        path: The path of the part relative to the archive, e.g.,
            "Pictures/image.jpg". Shortcuts like "content", "meta",
            "settings", "styles", and "manifest" are also supported.
            The path should use '/' as a separator.
        data: The `bytes` object containing the content to set for the part.

    Raises:
        ValueError: If the document's container is empty.

    """
    if not self.container:
        msg = "Empty Container"
        raise ValueError(msg)
    # "./ObjectReplacements/Object 1"
    path = path.lstrip("./")
    path = _get_part_path(path)
    cls = _get_part_class(path)
    # XML part overwritten
    if cls is not None:
        with contextlib.suppress(KeyError):
            del self.__xmlparts[path]
    self.container.set_part(path, data)

set_table_displayed

set_table_displayed(
    table: str | int, displayed: bool
) -> None

Set the table:display property of the table’s style.

This controls whether the table should be displayed in a graphical interface. If the table does not have an existing style, a new automatic style is created for it. This method replaces the broken Table.displayd() method from previous odfdo versions.

Parameters:

Name Type Description Default
table str | int

The name (str) or index (int) of the table.

required
displayed bool

A boolean flag; True to display the table, False to hide it.

required
Source code in odfdo/document.py
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
def set_table_displayed(self, table: str | int, displayed: bool) -> None:
    """Set the `table:display` property of the table's style.

    This controls whether the table should be displayed in a graphical
    interface. If the table does not have an existing style, a new
    automatic style is created for it. This method replaces the broken
    `Table.displayd()` method from previous `odfdo` versions.

    Args:
        table: The name (str) or index (int) of the table.
        displayed: A boolean flag; `True` to display the table, `False` to hide it.

    """
    orig_style = self.get_table_style(table)
    if not orig_style:
        name = self._unique_style_name("ta")
        orig_style = Element.from_tag(
            f'<style:style style:name="{name}" style:family="table" '
            'style:master-page-name="Default">'
            '<style:table-properties table:display="true" '
            'style:writing-mode="lr-tb"/></style:style>'
        )
        self.insert_style(orig_style, automatic=True)  # ty:ignore
    new_style = cast("Style", orig_style.clone)
    new_name = self._unique_style_name("ta")
    new_style.name = new_name
    self.insert_style(new_style, automatic=True)
    sheet = self._get_table(table)
    sheet.style = new_name  # ty: ignore
    properties = {"table:display": Boolean.encode(displayed)}
    new_style.set_properties(properties)

show_styles

show_styles(
    automatic: bool = True,
    common: bool = True,
    properties: bool = False,
) -> str

Provide a formatted string summary of styles in the document.

Parameters:

Name Type Description Default
automatic bool

If True, include automatic styles in the output.

True
common bool

If True, include common (non-automatic) styles.

True
properties bool

If True, include the individual properties of each style in the output.

False

Returns:

Type Description
str

A human-readable summary of the document’s styles.

Source code in odfdo/document.py
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
def show_styles(
    self,
    automatic: bool = True,
    common: bool = True,
    properties: bool = False,
) -> str:
    """Provide a formatted string summary of styles in the document.

    Args:
        automatic: If `True`, include automatic styles in the output.
        common: If `True`, include common (non-automatic) styles.
        properties: If `True`, include the individual properties
            of each style in the output.

    Returns:
        A human-readable summary of the document's styles.

    """
    infos = []
    for style in self.get_styles():
        try:
            name: str = style.name or ""
        except AttributeError:
            print("Style error:")
            print(style.__class__)
            print(style.serialize())
            raise
        if style.__class__.__name__ == "DrawFillImage":
            family = ""
        else:
            family = str(style.family)
        parent = style.parent
        is_auto = parent and parent.tag == "office:automatic-styles"
        if (is_auto and automatic is False) or (not is_auto and common is False):
            continue
        is_used = bool(self.get_styled_elements(name))
        if isinstance(style, StyleBase) and properties:
            style_properties = style.get_properties()
        else:
            style_properties = None
        infos.append(
            {
                "type": "auto  " if is_auto else "common",
                "used": "y" if is_used else "n",
                "family": family,
                "parent": self._pseudo_style_attribute(style, "parent_style") or "",
                "name": name or "",
                "display_name": self._pseudo_style_attribute(style, "display_name")
                or "",
                "properties": style_properties,
            }
        )
    if not infos:
        return ""
    # Sort by family and name
    infos.sort(key=itemgetter("family", "name"))
    # Show common and used first
    infos.sort(key=itemgetter("type", "used"), reverse=True)
    max_family = str(max(len(x["family"]) for x in infos))  # ty: ignore
    max_parent = str(max(len(x["parent"]) for x in infos))  # ty: ignore
    formater = (
        "%(type)s used:%(used)s family:%(family)-0"
        + max_family
        + "s parent:%(parent)-0"
        + max_parent
        + "s name:%(name)s"
    )
    output = []
    for info in infos:
        line = formater % info
        if info["display_name"]:
            line += " display_name:" + info["display_name"]  # ty: ignore
        output.append(line)
        if info["properties"]:
            for name, value in info["properties"].items():
                output.append(f"   - {name}: {value}")
    output.append("")
    return "\n".join(output)

to_dict

to_dict(
    table: str | int | None = None,
    orient: str = "list",
    header: bool = True,
    mode: str = "python",
    lstrip: bool = False,
    include_hidden: bool = False,
    no_decimal: bool = False,
    no_date: bool = False,
    no_nan: bool = False,
) -> dict[str, Any] | list[dict[str, Any]]

Export document table(s) as Python dictionaries.

Parameters:

Name Type Description Default
table str | int | None

Name or 0-based index of a specific table to export. If None, exports all tables in the document.

None
orient str

Format of the exported dictionary: - “list” (default): Columnar format {"col": [values, ...]}. - “records”: List of row dicts [{"col": value, ...}, ...]. - “matrix”: Dict mapping table names to 2D lists {"TableName": [[...], ...]}.

'list'
header bool

If True, uses the first row of data as column header keys.

True
mode str

Serialization mode (“python” or “json”). Defaults to “python”. “python” mode can be customized by arguments “no_decimal”, “no_date” and “no_nan”.

'python'
lstrip bool

If True, removes leading empty rows and columns from the top-left before export.

False
include_hidden bool

If True, include hidden tables.

False
no_decimal bool

If True in “python” mode, convert Decimal values to float or int.

False
no_date bool

If True in “python” mode, convert date, datetime, and timedelta values to ODF/ISO formatted strings.

False
no_nan bool

If True in “python” mode, convert NaN and infinity values to None.

False
Example

Table “product”:

reference color price
ref01 white 10,00
ref02 blue 20,50
ref03 red 25,75

document.to_dict() { ‘product’: { ‘reference’: [‘ref01’, ‘ref02’, ‘ref03’], ‘color’: [‘white’, ‘blue’, ‘red’], ‘price’: [10, Decimal(‘20.5’), Decimal(‘25.75’)] } }

document.to_dict(orient=”records”) { ‘product’: [ {‘reference’: ‘ref01’, ‘color’: ‘white’, ‘price’: 10}, {‘reference’: ‘ref02’, ‘color’: ‘blue’, ‘price’: Decimal(‘20.5’)}, {‘reference’: ‘ref03’, ‘color’: ‘red’, ‘price’: Decimal(‘25.75’)} ] }

document.to_dict(orient=”matrix”) { ‘product’: [ [‘reference’, ‘color’, ‘price’], [‘ref01’, ‘white’, 10], [‘ref02’, ‘blue’, Decimal(‘20.5’)], [‘ref03’, ‘red’, Decimal(‘25.75’)] ] }

Returns:

Type Description
dict[str, Any] | list[dict[str, Any]]

A dictionary of table dictionaries if table is None, or the

dict[str, Any] | list[dict[str, Any]]

dictionary for the specified table if table is given.

Raises:

Type Description
KeyError

If the specified table name is not found.

IndexError

If the specified table index is out of bounds.

ValueError

If orient is not one of “list”, “records”, or “matrix”.

Source code in odfdo/document.py
 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
def to_dict(
    self,
    table: str | int | None = None,
    orient: str = "list",
    header: bool = True,
    mode: str = "python",
    lstrip: bool = False,
    include_hidden: bool = False,
    no_decimal: bool = False,
    no_date: bool = False,
    no_nan: bool = False,
) -> dict[str, Any] | list[dict[str, Any]]:
    """Export document table(s) as Python dictionaries.

    Args:
        table: Name or 0-based index of a specific table to export. If
            None, exports all tables in the document.
        orient: Format of the exported dictionary:
            - "list" (default): Columnar format `{"col": [values, ...]}`.
            - "records": List of row dicts `[{"col": value, ...}, ...]`.
            - "matrix": Dict mapping table names to 2D lists
              `{"TableName": [[...], ...]}`.
        header: If True, uses the first row of data as column header keys.
        mode: Serialization mode ("python" or "json"). Defaults to
            "python". "python" mode can be customized by arguments
            "no_decimal", "no_date" and "no_nan".
        lstrip: If True, removes leading empty rows and columns from the
            top-left before export.
        include_hidden: If True, include hidden tables.
        no_decimal: If True in "python" mode, convert Decimal values to
            float or int.
        no_date: If True in "python" mode, convert date, datetime, and
            timedelta values to ODF/ISO formatted strings.
        no_nan: If True in "python" mode, convert NaN and infinity values
            to None.

    Example:
        Table "product":

        | reference | color | price |
        |-----------|-------|-------|
        | ref01     | white | 10,00 |
        | ref02     | blue  | 20,50 |
        | ref03     | red   | 25,75 |

    >>> document.to_dict()
    {
        'product': {
            'reference': ['ref01', 'ref02', 'ref03'],
            'color': ['white', 'blue', 'red'],
            'price': [10, Decimal('20.5'), Decimal('25.75')]
        }
    }

    >>> document.to_dict(orient="records")
    {
        'product': [
            {'reference': 'ref01', 'color': 'white', 'price': 10},
            {'reference': 'ref02', 'color': 'blue', 'price': Decimal('20.5')},
            {'reference': 'ref03', 'color': 'red', 'price': Decimal('25.75')}
        ]
    }

    >>> document.to_dict(orient="matrix")
    {
        'product': [
            ['reference', 'color', 'price'],
            ['ref01', 'white', 10],
            ['ref02', 'blue', Decimal('20.5')],
            ['ref03', 'red', Decimal('25.75')]
        ]
    }

    Returns:
        A dictionary of table dictionaries if `table` is None, or the
        dictionary for the specified table if `table` is given.

    Raises:
        KeyError: If the specified table name is not found.
        IndexError: If the specified table index is out of bounds.
        ValueError: If `orient` is not one of "list", "records", or "matrix".

    """
    if orient not in ("list", "records", "matrix"):
        msg = (
            f"Invalid orient parameter: {orient!r}. "
            "Expected 'list', 'records', or 'matrix'"
        )
        raise ValueError(msg)
    if table is not None:
        if isinstance(table, int):
            tables = self.body.tables
            if table < 0 or table >= len(tables):
                msg = f"Table index {table} out of range (0..{len(tables) - 1})"
                raise IndexError(msg)
            target_table = tables[table]
        else:
            target_table = self.body.get_table_by_name(table)
            if not target_table:
                msg = f"Table {table!r} not found in document"
                raise KeyError(msg)
        return target_table.to_dict(
            orient=orient,
            header=header,
            mode=mode,
            lstrip=lstrip,
            no_decimal=no_decimal,
            no_date=no_date,
            no_nan=no_nan,
        )

    tables_dict: dict[str, Any] = {}
    unifyer = NameUnifyer()
    for t in self.body.tables:
        if not include_hidden and not self.get_table_displayed(t):
            continue
        name = unifyer.unique(t.name or "")
        table_dict = t.to_dict(
            orient=orient,
            header=header,
            mode=mode,
            lstrip=lstrip,
            no_decimal=no_decimal,
            no_date=no_date,
            no_nan=no_nan,
        )
        if orient == "matrix" and isinstance(table_dict, dict):
            tables_dict[name] = (
                next(iter(table_dict.values())) if table_dict else []
            )
        else:
            tables_dict[name] = table_dict
    return tables_dict

to_json

to_json(
    path_or_file: str | Path | None = None,
    include_hidden: bool = False,
    pretty: bool = False,
    ensure_ascii: bool = False,
) -> str | None

Export the values from all tables in the document to JSON format.

The JSON output is a dictionary mapping each table’s name to its 2D list of cell values (list of list of cell values).

Parameters:

Name Type Description Default
path_or_file str | Path | None

The path or file to save the JSON content to. If None, the JSON content is returned as a string.

None
include_hidden bool

If True, include hidden tables in the export. Defaults to False.

False
pretty bool

Use pretty formater. Defaults to False.

False
ensure_ascii bool

If True, non-ASCII characters are escaped. Defaults to False.

False

Returns:

Type Description
str | None

str | None: The JSON content as a string if path_or_file is None, otherwise None.

Source code in odfdo/document.py
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
def to_json(
    self,
    path_or_file: str | Path | None = None,
    include_hidden: bool = False,
    pretty: bool = False,
    ensure_ascii: bool = False,
) -> str | None:
    """Export the values from all tables in the document to JSON format.

    The JSON output is a dictionary mapping each table's name to its 2D
    list of cell values (list of list of cell values).

    Args:
        path_or_file: The path or file to save the JSON content to.
            If None, the JSON content is returned as a string.
        include_hidden: If True, include hidden tables in the export.
            Defaults to False.
        pretty: Use pretty formater. Defaults to False.
        ensure_ascii: If True, non-ASCII characters are escaped.
            Defaults to False.

    Returns:
        str | None: The JSON content as a string if `path_or_file` is
            None, otherwise None.

    """
    tables_dict: dict[str, list[list[Any]]] = {}
    unifyer = NameUnifyer()

    for table in self.body.tables:
        if not include_hidden and not self.get_table_displayed(table):
            continue
        name = unifyer.unique(table.name or "")
        tables_dict[name] = serialize_table(table, "json")

    if pretty:
        content_str = format_json(tables_dict, ensure_ascii=ensure_ascii)
    else:
        content_str = json.dumps(
            tables_dict, ensure_ascii=ensure_ascii, allow_nan=False
        )

    if path_or_file:
        Path(path_or_file).write_text(content_str, encoding="utf-8")
        return None
    return content_str

to_markdown

to_markdown() -> str | list[TableMarkdown]

Export the document content to Markdown format.

For text documents (.odt), returns a single Markdown string. For spreadsheet documents (.ods), returns a list of TableMarkdown tuples (one per table) containing the filename and Markdown table string.

Returns:

Type Description
str | list[TableMarkdown]

str | list[TableMarkdown]: The Markdown representation of the document for text documents, or a list of TableMarkdown tuples for spreadsheets.

Raises:

Type Description
NotImplementedError

If the document type is not ‘text’ or ‘spreadsheet’.

Source code in odfdo/document.py
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
def to_markdown(self) -> str | list[TableMarkdown]:
    """Export the document content to Markdown format.

    For text documents (.odt), returns a single Markdown string.
    For spreadsheet documents (.ods), returns a list of TableMarkdown
    tuples (one per table) containing the filename and Markdown table
    string.

    Returns:
        str | list[TableMarkdown]: The Markdown representation of the
            document for text documents, or a list of TableMarkdown tuples
            for spreadsheets.

    Raises:
        NotImplementedError: If the document type is not 'text' or
            'spreadsheet'.

    """
    doc_type = self.get_type()
    if doc_type not in {"text", "spreadsheet"}:
        msg = f"Type of document {doc_type!r} not supported yet"
        raise NotImplementedError(msg)
    if doc_type == "text":
        return self._markdown_export_text()
    return self._markdown_export_tables()

TableMarkdown

Bases: NamedTuple

NamedTuple representing an exported markdown table from a spreadsheet.

Attributes:

Name Type Description
name str

The computed table identifier (e.g., ‘document#Table_1’).

content str

The markdown string content of the table.

Source code in odfdo/document.py
252
253
254
255
256
257
258
259
260
261
262
class TableMarkdown(NamedTuple):
    """NamedTuple representing an exported markdown table from a spreadsheet.

    Attributes:
        name (str): The computed table identifier (e.g., 'document#Table_1').
        content (str): The markdown string content of the table.

    """

    name: str
    content: str

content instance-attribute

content: str

name instance-attribute

name: str

_container_from_template

_container_from_template(
    template: str | Path | BytesIO,
) -> Container

Return a Container instance based on the provided template.

Parameters:

Name Type Description Default
template str | Path | BytesIO

The template to use. Can be a string representing a predefined template name (e.g., “text”), a file path (str or Path) to a custom template, or a file-like object (io.BytesIO).

required

Returns:

Type Description
Container

A new Container instance initialized from the template.

Source code in odfdo/document.py
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
def _container_from_template(template: str | Path | io.BytesIO) -> Container:
    """Return a Container instance based on the provided template.

    Args:
        template: The template to use. Can be a string representing a
            predefined template name (e.g., "text"), a file path (str or Path)
            to a custom template, or a file-like object (`io.BytesIO`).

    Returns:
        A new `Container` instance initialized from the template.

    """
    template_container = Container()
    if isinstance(template, str) and template in ODF_TEMPLATES:
        template = ODF_TEMPLATES[template]
        with rso.as_file(
            rso.files("odfdo.templates").joinpath(template)
        ) as template_path:
            template_container.open(template_path)
    else:
        # custom template
        template_container.open(template)
    # Return a copy of the template container
    container = template_container.clone
    # Change type from template to regular
    mimetype = container.mimetype.replace("-template", "")
    container.mimetype = mimetype
    # Update the manifest
    manifest = Manifest(ODF_MANIFEST, container)
    manifest.set_media_type("/", mimetype)
    container.set_part(ODF_MANIFEST, manifest.serialize())
    return container

_get_part_class

_get_part_class(path: str) -> type[XmlPart] | None

Get the specialized class for a core ODF XML part.

Parameters:

Name Type Description Default
path str

The full path of the XML part (e.g., “content.xml”).

required

Returns:

Type Description
type[XmlPart] | None

type[XmlPart] | None: The class corresponding to the part (e.g., Content for “content.xml”), or None if the part is not a recognized core XML part with a specialized class.

Source code in odfdo/document.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def _get_part_class(
    path: str,
) -> type[XmlPart] | None:
    """Get the specialized class for a core ODF XML part.

    Args:
        path: The full path of the XML part (e.g., "content.xml").

    Returns:
        type[XmlPart] | None: The class corresponding to the part
            (e.g., `Content` for "content.xml"), or `None` if the part
            is not a recognized core XML part with a specialized class.

    """
    name = Path(path).name
    return {
        ODF_CONTENT: Content,
        ODF_META: Meta,
        ODF_SETTINGS: Settings,
        ODF_STYLES: Styles,
        ODF_MANIFEST_NAME: Manifest,
    }.get(name)

_get_part_path

_get_part_path(path: str) -> str

Map a short name to the full path of a core ODF XML part.

For example, “content” is mapped to “content.xml”. If the path is not a recognized short name, it is returned unchanged.

Parameters:

Name Type Description Default
path str

The short name or full path of the part.

required

Returns:

Name Type Description
str str

The full path of the XML part.

Source code in odfdo/document.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def _get_part_path(path: str) -> str:
    """Map a short name to the full path of a core ODF XML part.

    For example, "content" is mapped to "content.xml". If the path is not
    a recognized short name, it is returned unchanged.

    Args:
        path: The short name or full path of the part.

    Returns:
        str: The full path of the XML part.

    """
    return {
        "content": ODF_CONTENT,
        "meta": ODF_META,
        "settings": ODF_SETTINGS,
        "styles": ODF_STYLES,
        "manifest": ODF_MANIFEST,
    }.get(path, path)

_show_styles

_show_styles(
    element: Element, level: int = 0
) -> str | None

Recursively generate a formatted string representation of a style element.

This function is used for creating a human-readable tree of styles, including their attributes and children.

Parameters:

Name Type Description Default
element Element

The style element to represent.

required
level int

The current nesting level for indentation and underlining.

0

Returns:

Type Description
str | None

str | None: A formatted string representing the style element, or None if the element is empty (no attributes or children).

Source code in odfdo/document.py
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
def _show_styles(element: Element, level: int = 0) -> str | None:
    """Recursively generate a formatted string representation of a style element.

    This function is used for creating a human-readable tree of styles,
    including their attributes and children.

    Args:
        element: The style element to represent.
        level: The current nesting level for indentation and underlining.

    Returns:
        str | None: A formatted string representing the style element, or
            `None` if the element is empty (no attributes or children).

    """
    output: list[str] = []
    attributes = element.attributes
    children = element.children
    # Don't show the empty elements
    if not attributes and not children:
        return None
    tag_name = element.tag
    output.append(tag_name)
    # Underline the name
    output.append(_underline_string(level, tag_name))
    # Add a separation between name and attributes
    output[-1] += "\n"

    # Attributes
    attrs: list[str] = []
    for key, value in attributes.items():
        attrs.append(f"{key}: {value}")
    if attrs:
        attrs.sort()
        # Add a separation between attributes and children
        attrs[-1] += "\n"
        output.extend(attrs)

    # Children
    # Sort children according to their names
    children2 = [(child.tag, child) for child in children]
    children2.sort()
    children = [child for name, child in children2]
    for child in children:
        child_output = _show_styles(child, level + 1)
        if child_output:
            output.append(child_output)
    return "\n".join(output)

_template_container cached

_template_container(doc_type: str) -> Container | None

Return a raw template container for the given document type.

Source code in odfdo/document.py
238
239
240
241
242
243
244
245
246
247
248
249
@cache
def _template_container(doc_type: str) -> Container | None:
    """Return a raw template container for the given document type."""
    template_file = ODF_TEMPLATES.get(doc_type)
    if not template_file:
        return None
    container = Container()
    with rso.as_file(
        rso.files("odfdo.templates").joinpath(template_file)
    ) as template_path:
        container.open(template_path)
    return container

_underline_string

_underline_string(level: int, name: str) -> str

Generate an underline string for a given name and level.

Uses a predefined set of characters for underlining, based on the level. If the level is out of bounds, returns a newline.

Parameters:

Name Type Description Default
level int

The nesting level, which determines the underline character.

required
name str

The string to be underlined. The length of this string determines the length of the underline.

required

Returns:

Name Type Description
str str

The underline string, or a newline if the level is too high.

Source code in odfdo/document.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def _underline_string(level: int, name: str) -> str:
    """Generate an underline string for a given name and level.

    Uses a predefined set of characters for underlining, based on the `level`.
    If the level is out of bounds, returns a newline.

    Args:
        level: The nesting level, which determines the underline character.
        name: The string to be underlined. The length of this string
            determines the length of the underline.

    Returns:
        str: The underline string, or a newline if the level is too high.

    """
    if level >= len(UNDERLINE_LVL):
        return "\n"
    return UNDERLINE_LVL[level] * len(name)