Skip to main content

docxide_pdf/
lib.rs

1mod docx;
2mod error;
3mod fonts;
4mod geometry;
5mod math;
6mod model;
7mod pdf;
8
9pub use error::Error;
10
11use std::path::{Path, PathBuf};
12use std::time::Instant;
13
14/// Which view of a document's tracked changes to print.
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub enum RevisionView {
17    /// Word's "No Markup": insertions plain, deletions dropped. What Word's
18    /// online export prints.
19    #[default]
20    Final,
21    /// Word's "All Markup", inline: insertions underlined and deletions
22    /// struck through in the author's colour, deleted text kept in the
23    /// layout, a change bar in the margin beside every revised line.
24    Markup,
25}
26
27/// Per-conversion settings. The defaults reproduce Word's online export; each
28/// option moves one behaviour towards desktop Word or adapts the conversion to
29/// its host. Explicit options never read the environment;
30/// [`ConvertOptions::from_env`] reads the same settings from `DOCXIDE_*`
31/// variables and is what the functions without an options argument use.
32#[derive(Clone, Debug)]
33#[non_exhaustive]
34pub struct ConvertOptions {
35    /// Which view of the tracked changes to print. Environment:
36    /// `DOCXIDE_REVISIONS=markup`.
37    pub revisions: RevisionView,
38    /// Resample pictures shown above 192 ppi down to 192 ppi, as Word's online
39    /// export does. `false` keeps the source pixels, like a desktop export
40    /// with picture compression off. Environment: `DOCXIDE_NO_RESAMPLE=1`.
41    pub resample_pictures: bool,
42    /// Font directories searched before the system ones; the first listed
43    /// wins. Environment: `DOCXIDE_FONTS`, colon-separated (`;` on Windows).
44    pub font_dirs: Vec<PathBuf>,
45    /// Read and write the font index disk cache. Environment:
46    /// `DOCXIDE_NO_FONT_CACHE=1` switches it off.
47    pub font_cache: bool,
48    /// Draw the float wrap zones on the page. Environment:
49    /// `DOCXIDE_DEBUG_WRAP=1`.
50    pub debug_wrap: bool,
51}
52
53impl Default for ConvertOptions {
54    fn default() -> Self {
55        Self {
56            revisions: RevisionView::Final,
57            resample_pictures: true,
58            font_dirs: Vec::new(),
59            font_cache: true,
60            debug_wrap: false,
61        }
62    }
63}
64
65impl ConvertOptions {
66    /// Word's online export behaviour.
67    pub fn new() -> Self {
68        Self::default()
69    }
70
71    /// The defaults overridden by whichever `DOCXIDE_*` variables are set. A
72    /// boolean variable is on unless its value is empty, `0` or `false`.
73    pub fn from_env() -> Self {
74        Self::from_vars(|name| std::env::var(name).ok())
75    }
76
77    fn from_vars(var: impl Fn(&str) -> Option<String>) -> Self {
78        let flag = |name: &str| {
79            var(name).is_some_and(|v| {
80                !matches!(v.trim().to_ascii_lowercase().as_str(), "" | "0" | "false")
81            })
82        };
83        let mut options = Self::new();
84        if var("DOCXIDE_REVISIONS").is_some_and(|v| v.trim().eq_ignore_ascii_case("markup")) {
85            options.revisions = RevisionView::Markup;
86        }
87        if flag("DOCXIDE_NO_RESAMPLE") {
88            options.resample_pictures = false;
89        }
90        if let Some(dirs) = var("DOCXIDE_FONTS") {
91            let sep = if cfg!(windows) { ';' } else { ':' };
92            options.font_dirs = dirs
93                .split(sep)
94                .map(str::trim)
95                .filter(|dir| !dir.is_empty())
96                .map(PathBuf::from)
97                .collect();
98        }
99        if flag("DOCXIDE_NO_FONT_CACHE") {
100            options.font_cache = false;
101        }
102        if flag("DOCXIDE_DEBUG_WRAP") {
103            options.debug_wrap = true;
104        }
105        options
106    }
107
108    pub fn revisions(mut self, view: RevisionView) -> Self {
109        self.revisions = view;
110        self
111    }
112
113    pub fn resample_pictures(mut self, on: bool) -> Self {
114        self.resample_pictures = on;
115        self
116    }
117
118    pub fn font_dirs(mut self, dirs: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
119        self.font_dirs = dirs.into_iter().map(Into::into).collect();
120        self
121    }
122
123    pub fn font_cache(mut self, on: bool) -> Self {
124        self.font_cache = on;
125        self
126    }
127
128    pub fn debug_wrap(mut self, on: bool) -> Self {
129        self.debug_wrap = on;
130        self
131    }
132
133    pub(crate) fn font_setup(&self) -> fonts::FontSetup {
134        fonts::FontSetup {
135            dirs: self.font_dirs.clone(),
136            cache: self.font_cache,
137        }
138    }
139}
140
141/// Converts with [`ConvertOptions::from_env`].
142pub fn convert_docx_to_pdf(input: impl AsRef<Path>, path: impl AsRef<Path>) -> Result<(), Error> {
143    convert_docx_to_pdf_with(input, path, &ConvertOptions::from_env())
144}
145
146pub fn convert_docx_to_pdf_with(
147    input: impl AsRef<Path>,
148    path: impl AsRef<Path>,
149    options: &ConvertOptions,
150) -> Result<(), Error> {
151    reject_old_env_vars()?;
152    let doc = docx::parse(input.as_ref(), options.revisions)?;
153    render_and_write(&doc, path, options)
154}
155
156/// Converts with [`ConvertOptions::from_env`].
157pub fn convert_docx_bytes_to_pdf(input: &[u8], path: impl AsRef<Path>) -> Result<(), Error> {
158    convert_docx_bytes_to_pdf_with(input, path, &ConvertOptions::from_env())
159}
160
161pub fn convert_docx_bytes_to_pdf_with(
162    input: &[u8],
163    path: impl AsRef<Path>,
164    options: &ConvertOptions,
165) -> Result<(), Error> {
166    reject_old_env_vars()?;
167    let doc = docx::parse_bytes(input, options.revisions)?;
168    render_and_write(&doc, path, options)
169}
170
171/// For callers that serve or store the PDF themselves (web handlers, databases,
172/// wasm). Converts with [`ConvertOptions::from_env`].
173pub fn convert_docx_bytes_to_pdf_bytes(input: &[u8]) -> Result<Vec<u8>, Error> {
174    convert_docx_bytes_to_pdf_bytes_with(input, &ConvertOptions::from_env())
175}
176
177pub fn convert_docx_bytes_to_pdf_bytes_with(
178    input: &[u8],
179    options: &ConvertOptions,
180) -> Result<Vec<u8>, Error> {
181    reject_old_env_vars()?;
182    let doc = docx::parse_bytes(input, options.revisions)?;
183    pdf::render(&doc, options)
184}
185
186/// The variables lost their old `DOCXSIDE_` prefix; failing loudly beats silently
187/// dropping someone's font directories and rendering with fallbacks.
188fn reject_old_env_vars() -> Result<(), Error> {
189    match old_env_var(std::env::vars_os().map(|(key, _)| key)) {
190        Some(name) => Err(Error::RenamedEnvVar(name)),
191        None => Ok(()),
192    }
193}
194
195fn old_env_var(keys: impl Iterator<Item = std::ffi::OsString>) -> Option<String> {
196    keys.filter_map(|key| key.into_string().ok())
197        .find(|key| key.starts_with("DOCXSIDE_"))
198}
199
200fn render_and_write(
201    doc: &model::Document,
202    path: impl AsRef<Path>,
203    options: &ConvertOptions,
204) -> Result<(), Error> {
205    let path = path.as_ref().with_extension("pdf");
206    let t0 = Instant::now();
207
208    let bytes = pdf::render(doc, options)?;
209    let t_render = t0.elapsed();
210
211    std::fs::write(&path, &bytes)?;
212    let t_total = t0.elapsed();
213
214    log::info!(
215        "Timing: render={:.1}ms, write={:.1}ms, total={:.1}ms (output {} bytes)",
216        t_render.as_secs_f64() * 1000.0,
217        (t_total - t_render).as_secs_f64() * 1000.0,
218        t_total.as_secs_f64() * 1000.0,
219        bytes.len(),
220    );
221
222    Ok(())
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn old_prefix_is_reported_with_its_new_name() {
231        let keys = ["PATH", "DOCXIDE_FONTS", "DOCXSIDE_FONTS"].map(Into::into);
232        let old = old_env_var(keys.into_iter()).unwrap();
233        assert_eq!(
234            Error::RenamedEnvVar(old).to_string(),
235            "DOCXSIDE_FONTS is no longer read; rename it to DOCXIDE_FONTS"
236        );
237        assert_eq!(old_env_var(["DOCXIDE_FONTS".into()].into_iter()), None);
238    }
239
240    #[test]
241    fn env_vars_override_the_online_defaults() {
242        let with = |vars: &[(&str, &str)]| {
243            ConvertOptions::from_vars(|name| {
244                vars.iter()
245                    .find(|(n, _)| *n == name)
246                    .map(|(_, v)| v.to_string())
247            })
248        };
249        let plain = with(&[]);
250        assert_eq!(plain.revisions, RevisionView::Final);
251        assert!(plain.resample_pictures && plain.font_cache && !plain.debug_wrap);
252        assert!(plain.font_dirs.is_empty());
253        for off in ["0", "false", "", " False "] {
254            assert!(with(&[("DOCXIDE_NO_RESAMPLE", off)]).resample_pictures);
255        }
256        for not_markup in ["", "final", "1"] {
257            assert_eq!(
258                with(&[("DOCXIDE_REVISIONS", not_markup)]).revisions,
259                RevisionView::Final
260            );
261        }
262        let fonts = if cfg!(windows) {
263            " a ; ;b;c "
264        } else {
265            " a : :b:c "
266        };
267        let set = with(&[
268            ("DOCXIDE_REVISIONS", " Markup "),
269            ("DOCXIDE_NO_RESAMPLE", "1"),
270            ("DOCXIDE_NO_FONT_CACHE", "yes"),
271            ("DOCXIDE_DEBUG_WRAP", "true"),
272            ("DOCXIDE_FONTS", fonts),
273        ]);
274        assert_eq!(set.revisions, RevisionView::Markup);
275        assert!(!set.resample_pictures && !set.font_cache && set.debug_wrap);
276        assert_eq!(set.font_dirs, [PathBuf::from("a"), "b".into(), "c".into()]);
277        let built = ConvertOptions::new()
278            .revisions(RevisionView::Markup)
279            .resample_pictures(false)
280            .font_dirs(["x"])
281            .font_cache(false)
282            .debug_wrap(true);
283        assert_eq!(built.revisions, RevisionView::Markup);
284        assert!(!built.resample_pictures && !built.font_cache && built.debug_wrap);
285        assert_eq!(built.font_setup().dirs, [PathBuf::from("x")]);
286    }
287}