Skip to main content

f_office/
lib.rs

1//! Public API of F-Office.
2//!
3//! F-Office renders Office Open XML documents the way Microsoft Office does, starting with
4//! Word's DOCX format. This crate opens a file and lays it out into a display list, which
5//! `f-office-raster` draws as pixels, or writes it as a PDF file. The other `f-office-*` crates
6//! are internal and have no stability promise before 1.0.
7
8use std::fmt;
9
10pub mod edit;
11mod export;
12mod fidelity;
13mod incremental;
14mod pictures;
15#[cfg(any(test, feature = "development"))]
16pub mod suite;
17
18pub use fidelity::{
19    FidelityLevel, FidelityReport, FontMatchKind, FontStatus, MissingGlyphGroup, Omission,
20    OmissionKind,
21};
22pub use incremental::{LayoutContinuation, LayoutProgress, PreparedDocument};
23
24#[cfg(any(test, feature = "development"))]
25use f_office_docx::PlacedLine;
26use f_office_docx::TextMap;
27use f_office_fonts::FontDb;
28use f_office_opc::Package;
29
30/// The configuration: the setup of Word's machine and the user's choice of fonts, and the types
31/// of its keys.
32pub use f_office_docx::configuration;
33/// Why a target's ID names no target, or the configuration or the target's profile does not
34/// read: the error of `Target::from_str` and of [`Error::Configuration`].
35pub use f_office_docx::configuration::Error as ConfigurationError;
36pub use f_office_docx::{
37    ART_PICTURES_BYTE_LIMIT, ART_PICTURES_CLIP_DEPTH_LIMIT, ART_PICTURES_COMMAND_LIMIT,
38    ART_PICTURES_REACH_LIMIT, ART_PICTURES_SHAPE_LIMIT, ART_PICTURES_SIZE_LIMIT, Address,
39    AddressError, AddressStep, ArtPictures, ArtPicturesError, ArtPicturesFault, CellPlace,
40    Configuration, DateTime, EndHyphen, LineTextEnd, LineTurn, LinkTarget, NumberSeparators,
41    NumberSeparatorsError, StoryBookmark, StoryLink, StoryParagraph, Target, TextBlock,
42    TextBlockKind, TextCluster, TextLine, TextStory,
43};
44pub use f_office_fonts::FontDb as FontDatabase;
45pub use f_office_opc::{Limits, RandomAccessRead, XmlLimits};
46pub use f_office_paint::{DisplayList, ImageFault, ImageFormat, Page};
47pub use f_office_units::Length;
48pub use f_office_warnings::Name;
49
50/// The warnings of the DOCX layout, which [`Warning::Docx`] holds, and the types of their
51/// fields.
52pub mod docx {
53    pub use f_office_docx::{
54        ChartReason, Drawing, DrawingMlFeature, DrawingMlWarning, Feature, GroupTransform, Limit,
55        MatchedFont, MetafileRecordType, MetafileWarning, NoteKind, ReadAs, Reason,
56        SubstituteLayout, UnicodeBlock, ValuePlace, Warning,
57    };
58    pub use f_office_fonts::ShapeFailure;
59}
60
61/// The warnings of the PDF writer, which [`Warning::Pdf`] holds.
62pub mod pdf {
63    pub use f_office_pdf::Warning;
64}
65
66// A finished display list, and the document that holds
67// it, stay `Send + Sync`.
68const _: () = {
69    const fn shared<T: Send + Sync>() {}
70    shared::<DisplayList>();
71    shared::<Document>();
72};
73
74/// Timing spans of the rendering stages: `open` (the package),
75/// `docx` (reading the parts and the layout), `layout` (the layout passes inside `docx`) and
76/// `pdf` (writing the PDF file), recorded on a thread that called [`timing::arm`].
77#[cfg(feature = "timing")]
78pub mod timing {
79    pub use f_office_docx::timing::{arm, take};
80}
81
82/// Why a document could not be rendered.
83#[derive(Clone, Debug, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum Error {
86    /// The package could not be read.
87    Package(f_office_opc::Error),
88    /// The DOCX content could not be laid out.
89    Docx(f_office_docx::Error),
90    /// The pages could not be written as PDF.
91    Pdf(f_office_pdf::Error),
92    /// The configuration or the target's profile does not read.
93    Configuration(ConfigurationError),
94}
95
96impl fmt::Display for Error {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        f.write_str(match self {
99            Self::Package(_) => "the package could not be read",
100            Self::Docx(_) => "the DOCX content could not be laid out",
101            Self::Pdf(_) => "the pages could not be written as PDF",
102            Self::Configuration(_) => "the configuration or the target's profile does not read",
103        })
104    }
105}
106
107impl std::error::Error for Error {
108    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
109        Some(match self {
110            Self::Package(error) => error,
111            Self::Docx(error) => error,
112            Self::Pdf(error) => error,
113            Self::Configuration(error) => error,
114        })
115    }
116}
117
118/// What a rendering left out of the file, or drew in another way than the file asks, while it
119/// went on with the rest. A warning holds no content of the document, only the names that the
120/// file uses to point at a part or a font, cut and with printable characters only ([`Name`]).
121#[derive(Clone, Debug, PartialEq, Eq, Hash)]
122#[non_exhaustive]
123pub enum Warning {
124    /// A warning of the DOCX layout.
125    Docx(docx::Warning),
126    /// A warning of the PDF writer.
127    Pdf(pdf::Warning),
128    /// A picture whose file the target's PDF writer writes again, such as each JPEG file at
129    /// its quality, and that keeps its own file because its data does not decode.
130    PictureNotWrittenAgain {
131        /// The picture's format.
132        format: ImageFormat,
133    },
134    /// An edit changed a package that holds a digital signature, which no longer matches the
135    /// changed parts ([`edit::apply`]).
136    SignatureBroken,
137    /// A deleted block held the reference of a footnote or an endnote, whose note stays in its
138    /// part ([`edit::apply`]).
139    NoteKept,
140}
141
142impl Warning {
143    /// The warning's kind, a short name that stays the same across versions and holds no name
144    /// of the file, such as `font-substituted`, for a caller that counts warnings or writes them
145    /// where the names of the file may not go.
146    #[must_use]
147    pub fn kind(&self) -> &'static str {
148        match self {
149            Self::Docx(warning) => warning.kind(),
150            Self::Pdf(warning) => warning.kind(),
151            Self::PictureNotWrittenAgain { .. } => "picture-not-written-again",
152            Self::SignatureBroken => "signature-broken",
153            Self::NoteKept => "note-kept",
154        }
155    }
156}
157
158impl fmt::Display for Warning {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        match self {
161            Self::Docx(warning) => warning.fmt(f),
162            Self::Pdf(warning) => warning.fmt(f),
163            Self::PictureNotWrittenAgain { format } => write!(
164                f,
165                "a picture in {format} format keeps its own file, which the target's PDF writer \
166                 writes again: its data does not decode"
167            ),
168            Self::SignatureBroken => f.write_str(
169                "the package holds a digital signature, which the edits break: sign the new file again",
170            ),
171            Self::NoteKept => f.write_str(
172                "a deleted block held the reference of a footnote or an endnote, and the note stays in its part: delete it with a raw edit if it must go",
173            ),
174        }
175    }
176}
177
178/// The warnings of a call, each distinct warning once with the number of times it came.
179pub type Warnings = f_office_warnings::Warnings<Warning>;
180
181/// The value of a call with its warnings.
182pub type Warned<T> = f_office_warnings::Warned<T, Warning>;
183
184/// The error chain of `error`: its own text, then the text of each cause that
185/// [`source`](std::error::Error::source) gives, joined by `: `. Each error of F-Office writes only
186/// its own text and gives its cause through `source`, so a place that shows an error to a person
187/// writes this, so that the cause stays visible.
188#[must_use]
189pub fn error_chain(error: &dyn std::error::Error) -> String {
190    let mut text = error.to_string();
191    let mut cause = error.source();
192    while let Some(next) = cause {
193        text.push_str(": ");
194        text.push_str(&next.to_string());
195        cause = next.source();
196    }
197    text
198}
199
200/// Choices for opening a document that the document itself does not make. Start from
201/// [`Options::default`] and set the fields that differ, so that a new field breaks no caller.
202/// The default lays out for the default target with its defaults.
203#[derive(Clone, Debug, PartialEq, Eq)]
204#[non_exhaustive]
205pub struct Options {
206    /// The local date and time that `DATE` and `TIME` fields show, as Word shows the time of
207    /// printing. Without it, they show the results stored in the file, so that the same file
208    /// always gives the same pages.
209    pub now: Option<DateTime>,
210    /// The configuration of the pages: the target and the setup of Word's machine, such as the
211    /// resolution of the printer that Word lays out for ([`Configuration::of`]).
212    pub configuration: Configuration,
213    /// The development override of the target profile's values, such as quirk variants,
214    /// after the configuration.
215    #[cfg(any(test, feature = "development"))]
216    pub overrides: f_office_docx::profile::Overrides,
217    /// The limits that protect the readers against a hostile file: those of the ZIP file and
218    /// those of each XML part. A limit of the ZIP file that the file breaks stops the document
219    /// ([`Error::Package`]), with an error that names the limit. An XML part that breaks a limit
220    /// does not read, and the part policy decides: the main document part and the package's
221    /// relationships stop the document ([`Error::Docx`]), and another part is skipped with a
222    /// warning.
223    pub limits: Limits,
224}
225
226impl Default for Options {
227    fn default() -> Self {
228        Self {
229            now: None,
230            configuration: Configuration::of(Target::default()),
231            #[cfg(any(test, feature = "development"))]
232            overrides: f_office_docx::profile::Overrides::default(),
233            limits: Limits::default(),
234        }
235    }
236}
237
238impl Options {
239    /// Options for the base target, used by internal layout unit tests written against the base
240    /// profile.
241    #[cfg(test)]
242    pub(crate) fn base() -> Self {
243        Self {
244            configuration: Configuration::of(Target::base()),
245            ..Self::default()
246        }
247    }
248
249    /// The options of the layout: the same choices without the limits, which the package
250    /// carries to every reader of its parts.
251    fn layout(&self) -> f_office_docx::Options {
252        let mut layout = f_office_docx::Options::default();
253        layout.now = self.now;
254        layout.configuration = self.configuration.clone();
255        #[cfg(any(test, feature = "development"))]
256        {
257            layout.overrides = self.overrides.clone();
258        }
259        layout
260    }
261}
262
263/// A DOCX file opened and laid out once for a target: its display list, which an output draws or
264/// writes, the places of its lines, and the text blocks of its body. It holds no state of the
265/// parse or the layout: what the layout left out or drew in another way comes out of
266/// [`Document::open`] beside it.
267#[derive(Clone, Debug)]
268pub struct Document {
269    list: DisplayList,
270    #[cfg(any(test, feature = "development"))]
271    lines: Vec<PlacedLine>,
272    #[cfg(any(test, feature = "development"))]
273    tables: Vec<f_office_docx::TableColumns>,
274    text_blocks: Vec<TextBlock>,
275    text_map: TextMap,
276    fidelity: FidelityReport,
277}
278
279impl Document {
280    /// Opens a DOCX file and lays it out into pages for the target of `options`, with the
281    /// warnings of what it left out or drew in another way. The layout runs once, here.
282    ///
283    /// # Errors
284    ///
285    /// Returns an error when the file is not a readable DOCX package or its content cannot be
286    /// laid out, or when the configuration or the target's profile does not read.
287    pub fn open(docx: &[u8], fonts: &FontDb, options: &Options) -> Result<Warned<Self>, Error> {
288        Self::open_with_art(docx, fonts, &ArtPictures::new(), options)
289    }
290
291    /// Opens a DOCX file as [`Document::open`] does, with the pictures of the art page borders
292    /// `art`, which the caller adds beside the fonts ([`ArtPictures::add`]). A page border's side
293    /// of an art style whose picture `art` lacks is not drawn, with a warning.
294    ///
295    /// # Errors
296    ///
297    /// As [`Document::open`].
298    pub fn open_with_art(
299        docx: &[u8],
300        fonts: &FontDb,
301        art: &ArtPictures,
302        options: &Options,
303    ) -> Result<Warned<Self>, Error> {
304        Self::open_with((docx, fonts, art), &options.limits, &options.layout())
305    }
306
307    /// Opens a DOCX file from disk and lays it out into pages for the target of `options`,
308    /// reading only the ZIP central directory and the parts needed for layout without loading
309    /// the entire file into memory.
310    ///
311    /// # Errors
312    ///
313    /// Returns an error when the file cannot be opened as a DOCX package, its content cannot be
314    /// laid out, or the configuration or target profile does not read.
315    #[cfg(not(target_arch = "wasm32"))]
316    pub fn open_file(
317        path: &std::path::Path,
318        fonts: &FontDb,
319        options: &Options,
320    ) -> Result<Warned<Self>, Error> {
321        Self::open_file_with_art(path, fonts, &ArtPictures::new(), options)
322    }
323
324    /// Opens a DOCX file from disk as [`Document::open_file`] does, with art page-border
325    /// pictures `art`.
326    ///
327    /// # Errors
328    ///
329    /// As [`Document::open_file`].
330    #[cfg(not(target_arch = "wasm32"))]
331    pub fn open_file_with_art(
332        path: &std::path::Path,
333        fonts: &FontDb,
334        art: &ArtPictures,
335        options: &Options,
336    ) -> Result<Warned<Self>, Error> {
337        let package =
338            f_office_docx::timing::span("open", || Package::open_file(path, &options.limits))
339                .map_err(Error::Package)?;
340        Self::open_package((&package, fonts, art), &options.layout())
341    }
342
343    /// Opens a DOCX package from a caller-provided random-access byte source (such as a browser
344    /// `File.slice()` or OPFS sync handle) without copying the whole archive into memory.
345    ///
346    /// # Errors
347    ///
348    /// As [`Document::open`].
349    pub fn open_source(
350        source: std::sync::Arc<dyn RandomAccessRead>,
351        fonts: &FontDb,
352        options: &Options,
353    ) -> Result<Warned<Self>, Error> {
354        Self::open_source_with_art(source, fonts, &ArtPictures::new(), options)
355    }
356
357    /// Opens a DOCX package from a random-access byte source as [`Document::open_source`] does,
358    /// with art page-border pictures `art`.
359    ///
360    /// # Errors
361    ///
362    /// As [`Document::open`].
363    pub fn open_source_with_art(
364        source: std::sync::Arc<dyn RandomAccessRead>,
365        fonts: &FontDb,
366        art: &ArtPictures,
367        options: &Options,
368    ) -> Result<Warned<Self>, Error> {
369        let package =
370            f_office_docx::timing::span("open", || Package::open_source(source, &options.limits))
371                .map_err(Error::Package)?;
372        Self::open_package((&package, fonts, art), &options.layout())
373    }
374
375    /// Opens a DOCX file within `limits` with its fonts and art pictures, and lays it out with
376    /// the layout's own options, as [`Document::open_with_art`] does.
377    fn open_with(
378        (docx, fonts, art): (&[u8], &FontDb, &ArtPictures),
379        limits: &Limits,
380        layout: &f_office_docx::Options,
381    ) -> Result<Warned<Self>, Error> {
382        let package = f_office_docx::timing::span("open", || Package::open(docx, limits))
383            .map_err(Error::Package)?;
384        Self::open_package((&package, fonts, art), layout)
385    }
386
387    /// Lays out an already-indexed OPC `package` with `fonts`, `art`, and `layout`.
388    fn open_package(
389        (package, fonts, art): (&Package, &FontDb, &ArtPictures),
390        layout: &f_office_docx::Options,
391    ) -> Result<Warned<Self>, Error> {
392        let laid_out = f_office_docx::timing::span("docx", || {
393            f_office_docx::layout_lines(package, (fonts, art), layout)
394        })
395        .map_err(|error| match error {
396            f_office_docx::Error::Configuration(error) => Error::Configuration(error),
397            error => Error::Docx(error),
398        })?;
399        let (doc, warnings) = incremental::finish_laid_out(laid_out);
400        Ok(Warned::new(doc, warnings))
401    }
402
403    /// The display list of the pages, the only border between the layout and an output.
404    #[must_use]
405    pub fn display_list(&self) -> &DisplayList {
406        &self.list
407    }
408
409    /// Typed rendering fidelity summary derived from layout font records and warnings.
410    #[must_use]
411    pub fn fidelity(&self) -> &FidelityReport {
412        &self.fidelity
413    }
414
415    /// The pages in order: the pages of the display list ([`Document::display_list`]).
416    #[must_use]
417    pub fn pages(&self) -> &[Page] {
418        self.list.pages()
419    }
420
421    /// The number of pages.
422    #[must_use]
423    pub fn page_count(&self) -> usize {
424        self.pages().len()
425    }
426
427    /// The page at `index`, counted from 0, or none past the last page.
428    #[must_use]
429    pub fn page(&self, index: usize) -> Option<&Page> {
430        self.pages().get(index)
431    }
432
433    /// The width and the height of the page at `index`, counted from 0, without drawing it, or
434    /// none past the last page.
435    #[must_use]
436    pub fn page_size(&self, index: usize) -> Option<(Length, Length)> {
437        self.page(index).map(|page| (page.width(), page.height()))
438    }
439
440    /// The paragraphs and tables of the body in the order of the document, each with its
441    /// address, which counts from 1, its kind with its style and text, and the indices of the
442    /// pages that its lines lie on, which count from 0 as [`Document::page`] does. The pages are
443    /// those of this document's layout, so of the configuration that it was opened with
444    /// ([`Options::configuration`]): the same file can give other pages for another target.
445    /// The paragraphs of a table's cells follow the table. Headers, footers, notes and text
446    /// boxes are not text blocks.
447    #[must_use]
448    pub fn text_blocks(&self) -> &[TextBlock] {
449        &self.text_blocks
450    }
451
452    /// The text map of the page at `index`, counted from 0 (**Text map**): its lines in reading
453    /// order, the header first, then the body, the endnotes, the frames, the text boxes, the
454    /// footnotes and the footer.
455    /// Each line names its story and its paragraph in [`Document::story_text`], with its range
456    /// of the paragraph's text, its line box and its clusters in visual order with their edges
457    /// on the page. It is empty past the last page.
458    #[must_use]
459    pub fn text_map(&self, index: usize) -> Vec<TextLine> {
460        self.text_map.page(index)
461    }
462
463    /// The text maps of the pages at `indices`, each as [`Document::text_map`] gives it, from
464    /// one read of each story on them: a viewer that needs many pages, such as for a search,
465    /// reads the body once and not once for each page.
466    #[must_use]
467    pub fn text_maps(&self, indices: &[usize]) -> Vec<Vec<TextLine>> {
468        self.text_map.pages(indices)
469    }
470
471    /// The text of `story` by paragraph (**Story text**): the texts of the paragraph's laid out
472    /// lines joined, so that a field gives its shown result, a list label is given as drawn,
473    /// hidden text is left out, and an automatic hyphen at a wrap is not in it.
474    #[must_use]
475    pub fn story_text(&self, story: TextStory) -> Vec<StoryParagraph> {
476        self.text_map.story(story)
477    }
478
479    /// Writes the pages as a PDF file, with the fonts subset and embedded, and with the warnings
480    /// of the PDF writer.
481    ///
482    /// Each page becomes one PDF page of the same size, with every glyph at its laid out position
483    /// and with its text, so that a viewer can search and copy it. The same document and fonts
484    /// always give the same bytes.
485    ///
486    /// # Errors
487    ///
488    /// Returns an error when the pages cannot be written as PDF.
489    pub fn write_pdf(&self, fonts: &FontDb) -> Result<Warned<Vec<u8>>, Error> {
490        let pdf = f_office_docx::timing::span("pdf", || f_office_pdf::write_pdf(&self.list, fonts))
491            .map_err(Error::Pdf)?;
492        Ok(Warned::new(pdf.value, pdf.warnings.map(Warning::Pdf)))
493    }
494
495    /// Streams the pages directly as a PDF 1.7 document into `writer` without buffering the
496    /// complete PDF bytes in memory.
497    ///
498    /// # Errors
499    ///
500    /// Returns an error when the pages cannot be written as PDF or when writing to `writer` fails.
501    pub fn write_pdf_to<W: std::io::Write>(
502        &self,
503        fonts: &FontDb,
504        writer: &mut W,
505    ) -> Result<Warned<()>, Error> {
506        let pdf = f_office_docx::timing::span("pdf", || {
507            f_office_pdf::write_pdf_to(&self.list, fonts, writer)
508        })
509        .map_err(Error::Pdf)?;
510        Ok(Warned::new((), pdf.warnings.map(Warning::Pdf)))
511    }
512}
513
514#[cfg(test)]
515mod tests {
516    use super::{Document, Error, FontDb, Options, error_chain};
517
518    #[test]
519    fn says_the_warnings_of_the_output_with_their_kinds() {
520        use super::{ImageFault, ImageFormat, Warning, pdf};
521        let skipped = Warning::Pdf(pdf::Warning::ImageSkipped {
522            format: ImageFormat::Wmf,
523            fault: ImageFault::Format,
524        });
525        assert_eq!(skipped.kind(), "pdf-image-skipped");
526        assert_eq!(
527            skipped.to_string(),
528            "an image in WMF format is left out of the PDF: the output draws no image of this \
529             format"
530        );
531        let kept = Warning::PictureNotWrittenAgain {
532            format: ImageFormat::Jpeg,
533        };
534        assert_eq!(kept.kind(), "picture-not-written-again");
535        assert_eq!(
536            kept.to_string(),
537            "a picture in JPEG format keeps its own file, which the target's PDF writer writes \
538             again: its data does not decode"
539        );
540    }
541
542    #[test]
543    fn rejects_a_file_that_is_not_a_package_for_every_target() {
544        let error = Document::open(b"not a zip", &FontDb::new(), &Options::default()).unwrap_err();
545        assert!(matches!(error, Error::Package(_)));
546        assert_ne!(error.to_string(), "");
547        // The same error, with the same text and cause, for every target.
548        for target in super::Target::all() {
549            let options = Options {
550                configuration: super::Configuration::of(target),
551                ..Options::default()
552            };
553            let with = Document::open(b"not a zip", &FontDb::new(), &options).unwrap_err();
554            assert!(matches!(with, Error::Package(_)));
555            assert_eq!(error_chain(&with), error_chain(&error));
556        }
557    }
558
559    #[test]
560    fn gives_the_pdf_error_as_its_cause() {
561        let error = Error::Pdf(f_office_pdf::Error::NoPages);
562        assert_eq!(error.to_string(), "the pages could not be written as PDF");
563        let cause = std::error::Error::source(&error).map(ToString::to_string);
564        assert_eq!(cause.as_deref(), Some("the display list has no page"));
565    }
566
567    #[test]
568    fn writes_the_error_chain_down_to_the_first_cause() {
569        let error = Document::open(b"not a zip", &FontDb::new(), &Options::default()).unwrap_err();
570        let chain = error_chain(&error);
571        assert!(
572            chain.starts_with("the package could not be read: unreadable ZIP package: "),
573            "{chain}"
574        );
575        let docx = Error::Docx(f_office_docx::Error::Package(
576            f_office_opc::Error::NoMainDocument,
577        ));
578        assert_eq!(
579            error_chain(&docx),
580            "the DOCX content could not be laid out: the package could not be read: package has \
581             no main document"
582        );
583        let leaf = f_office_pdf::Error::NoPages;
584        assert_eq!(error_chain(&leaf), "the display list has no page");
585    }
586}
587
588#[cfg(test)]
589mod comment_tests;
590#[cfg(test)]
591mod layout_tests;
592#[cfg(test)]
593mod pdf_tests;
594#[cfg(test)]
595mod picture_tests;
596#[cfg(test)]
597mod test_fonts;
598#[cfg(test)]
599mod text_block_tests;