lo_odf 0.4.8

ODF package serializers for text, spreadsheet, presentation, drawing, formula, and database documents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use std::path::Path;

use lo_core::{escape_text, Metadata, Result, XmlBuilder};
use lo_zip::{write_zip_file, write_zip_to_vec, ZipEntry};

pub const MIME_ODT: &str = "application/vnd.oasis.opendocument.text";
pub const MIME_ODS: &str = "application/vnd.oasis.opendocument.spreadsheet";
pub const MIME_ODP: &str = "application/vnd.oasis.opendocument.presentation";
pub const MIME_ODG: &str = "application/vnd.oasis.opendocument.graphics";
pub const MIME_ODF: &str = "application/vnd.oasis.opendocument.formula";
// LibreOffice itself writes Base documents with mimetype
// `application/vnd.oasis.opendocument.base` (confirmed against biblio.odb and
// evolocal.odb shipped with LibreOffice 26.2); `.database` is not recognised
// and causes `Error: source file could not be loaded`.
pub const MIME_ODB: &str = "application/vnd.oasis.opendocument.base";

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExtraFile {
    pub path: String,
    pub media_type: String,
    pub data: Vec<u8>,
}

impl ExtraFile {
    pub fn new(
        path: impl Into<String>,
        media_type: impl Into<String>,
        data: impl Into<Vec<u8>>,
    ) -> Self {
        Self {
            path: path.into(),
            media_type: media_type.into(),
            data: data.into(),
        }
    }
}

pub fn content_root_attrs() -> Vec<(&'static str, String)> {
    vec![
        (
            "xmlns:office",
            "urn:oasis:names:tc:opendocument:xmlns:office:1.0".to_string(),
        ),
        (
            "xmlns:style",
            "urn:oasis:names:tc:opendocument:xmlns:style:1.0".to_string(),
        ),
        (
            "xmlns:text",
            "urn:oasis:names:tc:opendocument:xmlns:text:1.0".to_string(),
        ),
        (
            "xmlns:table",
            "urn:oasis:names:tc:opendocument:xmlns:table:1.0".to_string(),
        ),
        (
            "xmlns:draw",
            "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0".to_string(),
        ),
        (
            "xmlns:presentation",
            "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0".to_string(),
        ),
        ("xmlns:xlink", "http://www.w3.org/1999/xlink".to_string()),
        (
            "xmlns:fo",
            "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0".to_string(),
        ),
        (
            "xmlns:svg",
            "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0".to_string(),
        ),
        (
            "xmlns:math",
            "http://www.w3.org/1998/Math/MathML".to_string(),
        ),
        (
            "xmlns:meta",
            "urn:oasis:names:tc:opendocument:xmlns:meta:1.0".to_string(),
        ),
        ("xmlns:dc", "http://purl.org/dc/elements/1.1/".to_string()),
        (
            "xmlns:of",
            "urn:oasis:names:tc:opendocument:xmlns:of:1.2".to_string(),
        ),
        ("office:version", "1.3".to_string()),
    ]
}

fn meta_root_attrs() -> Vec<(&'static str, String)> {
    vec![
        (
            "xmlns:office",
            "urn:oasis:names:tc:opendocument:xmlns:office:1.0".to_string(),
        ),
        (
            "xmlns:meta",
            "urn:oasis:names:tc:opendocument:xmlns:meta:1.0".to_string(),
        ),
        ("xmlns:dc", "http://purl.org/dc/elements/1.1/".to_string()),
        ("office:version", "1.3".to_string()),
    ]
}

fn styles_root_attrs() -> Vec<(&'static str, String)> {
    vec![
        (
            "xmlns:office",
            "urn:oasis:names:tc:opendocument:xmlns:office:1.0".to_string(),
        ),
        (
            "xmlns:style",
            "urn:oasis:names:tc:opendocument:xmlns:style:1.0".to_string(),
        ),
        (
            "xmlns:text",
            "urn:oasis:names:tc:opendocument:xmlns:text:1.0".to_string(),
        ),
        (
            "xmlns:table",
            "urn:oasis:names:tc:opendocument:xmlns:table:1.0".to_string(),
        ),
        (
            "xmlns:draw",
            "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0".to_string(),
        ),
        (
            "xmlns:fo",
            "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0".to_string(),
        ),
        (
            "xmlns:svg",
            "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0".to_string(),
        ),
        (
            "xmlns:presentation",
            "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0".to_string(),
        ),
        ("office:version", "1.3".to_string()),
    ]
}

fn settings_root_attrs() -> Vec<(&'static str, String)> {
    vec![
        (
            "xmlns:office",
            "urn:oasis:names:tc:opendocument:xmlns:office:1.0".to_string(),
        ),
        ("office:version", "1.3".to_string()),
    ]
}

pub fn meta_xml(meta: &Metadata) -> String {
    let mut xml = XmlBuilder::new();
    xml.declaration();
    xml.open("office:document-meta", &meta_root_attrs());
    xml.open("office:meta", &[]);
    xml.element(
        "meta:generator",
        concat!("libreoffice-rs/", env!("CARGO_PKG_VERSION")),
        &[],
    );
    if !meta.title.is_empty() {
        xml.element("dc:title", &meta.title, &[]);
    }
    if !meta.subject.is_empty() {
        xml.element("dc:subject", &meta.subject, &[]);
    }
    if !meta.description.is_empty() {
        xml.element("dc:description", &meta.description, &[]);
    }
    if !meta.creator.is_empty() {
        xml.element("meta:initial-creator", &meta.creator, &[]);
        xml.element("dc:creator", &meta.creator, &[]);
    }
    if !meta.created.is_empty() {
        xml.element("meta:creation-date", &meta.created, &[]);
    }
    if !meta.modified.is_empty() {
        xml.element("dc:date", &meta.modified, &[]);
    }
    if !meta.keywords.is_empty() {
        xml.element("meta:keyword", &meta.keywords.join(", "), &[]);
    }
    xml.close();
    xml.close();
    xml.finish()
}

pub fn styles_xml() -> String {
    let mut xml = XmlBuilder::new();
    xml.declaration();
    xml.open("office:document-styles", &styles_root_attrs());
    xml.open("office:styles", &[]);
    xml.raw(
        r#"<style:style style:name="Standard" style:family="paragraph"><style:text-properties fo:font-size="11pt"/></style:style>"#,
    );
    xml.raw(
        r#"<style:style style:name="Strong" style:family="text"><style:text-properties fo:font-weight="bold" style:font-weight-asian="bold"/></style:style>"#,
    );
    xml.raw(
        r#"<style:style style:name="Emphasis" style:family="text"><style:text-properties fo:font-style="italic" style:font-style-asian="italic"/></style:style>"#,
    );
    xml.raw(
        r#"<style:style style:name="Code" style:family="text"><style:text-properties style:font-name="monospace"/></style:style>"#,
    );
    // Heading paragraph styles, referenced by lo_writer when emitting
    // text:h elements. Names use LibreOffice's `_20_` space-escape.
    for level in 1..=6 {
        xml.raw(&format!(
            "<style:style style:name=\"Heading_20_{level}\" style:display-name=\"Heading {level}\" \
style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:next-style-name=\"Standard\">\
<style:text-properties fo:font-size=\"{size}pt\" fo:font-weight=\"bold\"/>\
</style:style>",
            level = level,
            size = 20 - (level - 1) * 2,
        ));
    }
    // Bullet list style shared across writer + impress.
    xml.raw(
        "<text:list-style style:name=\"L1\">\
<text:list-level-style-bullet text:level=\"1\" text:bullet-char=\"•\">\
<style:list-level-properties text:space-before=\"6mm\" text:min-label-width=\"5mm\"/>\
</text:list-level-style-bullet>\
</text:list-style>",
    );
    xml.close();
    // Page layout + default master page so presentation/drawing documents can
    // reference draw:master-page-name="Default". Writer/Calc ignore this.
    xml.raw(
        "<office:automatic-styles>\
<style:page-layout style:name=\"PL1\">\
<style:page-layout-properties fo:page-width=\"254mm\" fo:page-height=\"190.5mm\" \
fo:margin-top=\"0mm\" fo:margin-bottom=\"0mm\" fo:margin-left=\"0mm\" fo:margin-right=\"0mm\" \
style:print-orientation=\"landscape\"/>\
</style:page-layout>\
</office:automatic-styles>",
    );
    xml.raw(
        "<office:master-styles>\
<style:master-page style:name=\"Default\" style:page-layout-name=\"PL1\"/>\
</office:master-styles>",
    );
    xml.close();
    xml.finish()
}

pub fn settings_xml() -> String {
    let mut xml = XmlBuilder::new();
    xml.declaration();
    xml.open("office:document-settings", &settings_root_attrs());
    xml.empty("office:settings", &[]);
    xml.close();
    xml.finish()
}

pub fn manifest_xml(mimetype: &str, extras: &[ExtraFile]) -> String {
    let mut xml = XmlBuilder::new();
    xml.declaration();
    xml.open(
        "manifest:manifest",
        &[
            (
                "xmlns:manifest",
                "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0".to_string(),
            ),
            ("manifest:version", "1.3".to_string()),
        ],
    );
    xml.empty(
        "manifest:file-entry",
        &[
            ("manifest:full-path", "/".to_string()),
            ("manifest:media-type", mimetype.to_string()),
        ],
    );
    for component in ["content.xml", "styles.xml", "meta.xml", "settings.xml"] {
        xml.empty(
            "manifest:file-entry",
            &[
                ("manifest:full-path", component.to_string()),
                ("manifest:media-type", "text/xml".to_string()),
            ],
        );
    }
    for extra in extras {
        xml.empty(
            "manifest:file-entry",
            &[
                ("manifest:full-path", extra.path.clone()),
                ("manifest:media-type", extra.media_type.clone()),
            ],
        );
    }
    xml.close();
    xml.finish()
}

fn build_package_entries(
    mimetype: &str,
    content_xml: String,
    meta: &Metadata,
    extras: Vec<ExtraFile>,
) -> Vec<ZipEntry> {
    let mut entries = Vec::new();
    entries.push(ZipEntry::new("mimetype", mimetype.as_bytes().to_vec()));
    entries.push(ZipEntry::new("content.xml", content_xml.into_bytes()));
    entries.push(ZipEntry::new("styles.xml", styles_xml().into_bytes()));
    entries.push(ZipEntry::new("meta.xml", meta_xml(meta).into_bytes()));
    entries.push(ZipEntry::new("settings.xml", settings_xml().into_bytes()));
    entries.push(ZipEntry::new(
        "META-INF/manifest.xml",
        manifest_xml(mimetype, &extras).into_bytes(),
    ));
    for extra in extras {
        entries.push(ZipEntry::new(extra.path, extra.data));
    }
    entries
}

pub fn package_document(
    path: impl AsRef<Path>,
    mimetype: &str,
    content_xml: String,
    meta: &Metadata,
    extras: Vec<ExtraFile>,
) -> Result<()> {
    let entries = build_package_entries(mimetype, content_xml, meta, extras);
    write_zip_file(path, &entries)
}

/// Serialize an ODF package to bytes. Mirrors [`package_document`] but
/// returns the archive as a `Vec<u8>` instead of writing to disk, so byte
/// stream converters (`lo_odf::save_*_bytes`) can reuse the same layout.
pub fn package_document_bytes(
    mimetype: &str,
    content_xml: String,
    meta: &Metadata,
    extras: Vec<ExtraFile>,
) -> Result<Vec<u8>> {
    let entries = build_package_entries(mimetype, content_xml, meta, extras);
    write_zip_to_vec(&entries)
}

pub fn image_extras(images: Vec<(String, String, Vec<u8>)>) -> Vec<ExtraFile> {
    images
        .into_iter()
        .map(|(name, media_type, data)| {
            ExtraFile::new(format!("Pictures/{name}"), media_type, data)
        })
        .collect()
}

pub fn escaped_text_paragraph(text: &str) -> String {
    format!("<text:p>{}</text:p>", escape_text(text))
}

/// Write a Base document archive.
///
/// Base documents use a leaner layout than the other ODF files: no meta.xml
/// or styles.xml, just content.xml + settings.xml + manifest. The manifest
/// only lists the parts that actually exist.
pub fn package_database_document(
    path: impl AsRef<Path>,
    content_xml: String,
    extras: Vec<ExtraFile>,
) -> Result<()> {
    let mut entries = Vec::new();
    entries.push(ZipEntry::new("mimetype", MIME_ODB.as_bytes().to_vec()));
    entries.push(ZipEntry::new("content.xml", content_xml.into_bytes()));
    entries.push(ZipEntry::new("settings.xml", settings_xml().into_bytes()));

    // Manifest that only lists parts actually in this archive.
    let mut xml = XmlBuilder::new();
    xml.declaration();
    xml.open(
        "manifest:manifest",
        &[
            (
                "xmlns:manifest",
                "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0".to_string(),
            ),
            ("manifest:version", "1.3".to_string()),
        ],
    );
    xml.empty(
        "manifest:file-entry",
        &[
            ("manifest:full-path", "/".to_string()),
            ("manifest:version", "1.3".to_string()),
            ("manifest:media-type", MIME_ODB.to_string()),
        ],
    );
    xml.empty(
        "manifest:file-entry",
        &[
            ("manifest:full-path", "content.xml".to_string()),
            ("manifest:media-type", "text/xml".to_string()),
        ],
    );
    xml.empty(
        "manifest:file-entry",
        &[
            ("manifest:full-path", "settings.xml".to_string()),
            ("manifest:media-type", "text/xml".to_string()),
        ],
    );
    for extra in &extras {
        xml.empty(
            "manifest:file-entry",
            &[
                ("manifest:full-path", extra.path.clone()),
                ("manifest:media-type", extra.media_type.clone()),
            ],
        );
    }
    xml.close();
    entries.push(ZipEntry::new(
        "META-INF/manifest.xml",
        xml.finish().into_bytes(),
    ));
    for extra in extras {
        entries.push(ZipEntry::new(extra.path, extra.data));
    }
    write_zip_file(path, &entries)
}