mod body;
mod omml;
#[cfg(test)]
pub(crate) use omml::inline_math;
mod parts;
mod table;
mod xml;
use super::assets::MARK;
use super::zip::{Compression, ZipWriter};
use super::{Equations, doc_title};
use crate::analysis::pipeline::Analysis;
use crate::backend::PdfFile;
use crate::model::{ImageSpec, PictureFormat};
use crate::render::Pictures;
use parts::{
APP_PROPS, CONTENT_TYPES, DOCUMENT_NAMESPACES, FOOTNOTES_REL, FOOTNOTES_TYPE, PACKAGE_RELS, SETTINGS, STYLES,
XML_DECL, core_props, document_rels, footnotes_xml,
};
#[derive(Debug, Clone)]
pub struct DocxOptions {
pub scale: f32,
pub jobs: usize,
pub equations: Equations,
}
impl Default for DocxOptions {
fn default() -> Self {
Self {
scale: 3.0,
jobs: 0,
equations: Equations::MathMl,
}
}
}
pub(crate) struct PendingImage {
spec: ImageSpec,
width_emu: u64,
height_emu: u64,
alt: String,
hint: &'static str,
}
pub struct DocxOutput {
pub docx: Vec<u8>,
pub files: Vec<(String, Vec<u8>)>,
}
const SVG_BLIP_EXT: &str = "{96DAC541-7B7A-43D3-8B79-37D633B846F1}";
const SVG_BLIP_NS: &str = "http://schemas.microsoft.com/office/drawing/2016/SVG/main";
type DrawnPicture = (Vec<u8>, PictureFormat, Option<std::sync::Arc<[u8]>>);
#[derive(Default)]
struct Media {
files: Vec<(String, Vec<u8>)>,
rels: Vec<(String, String)>,
shown: Vec<(usize, &'static str)>,
}
impl Media {
fn add(&mut self, data: Vec<u8>, ext: &str) -> String {
let number = self.files.len() + 1;
let id = format!("rIdImg{number}");
self.rels.push((id.clone(), format!("media/image{number}.{ext}")));
self.files.push((format!("word/media/image{number}.{ext}"), data));
id
}
fn has_svg(&self) -> bool {
self.files.iter().any(|(name, _)| name.ends_with(".svg"))
}
}
pub fn render_docx(analysis: &Analysis, pdf: Option<&PdfFile>, opts: &DocxOptions) -> Vec<u8> {
write_package(analysis, pdf, opts).0
}
pub fn render_docx_with_images(
analysis: &Analysis,
pdf: Option<&PdfFile>,
opts: &DocxOptions,
image_dir: &str,
) -> DocxOutput {
let (docx, mut media) = write_package(analysis, pdf, opts);
let files = media
.shown
.iter()
.enumerate()
.map(|(i, &(file, hint))| {
let (name, data) = std::mem::take(&mut media.files[file]);
let ext = match name.rsplit_once('.') {
Some((_, "jpeg")) => "jpg",
Some((_, "svg")) => "svg",
_ => "png",
};
(format!("{image_dir}/{:03}-{hint}.{ext}", i + 1), data)
})
.collect();
DocxOutput { docx, files }
}
fn write_package(analysis: &Analysis, pdf: Option<&PdfFile>, opts: &DocxOptions) -> (Vec<u8>, Media) {
let attached = crate::render::notes::footnotes_attached(analysis);
let analysis = attached.as_ref().unwrap_or(analysis);
let doc = &analysis.doc;
let mut body = body::Body::new(doc, opts);
body.write(doc);
let pictures = Pictures::new(pdf, doc);
let drawn = crate::common::parallel::map(
body.images.len(),
opts.jobs,
|| pictures.renderer(),
|renderer, i| {
let spec = &body.images[i].spec;
let (data, format) = pictures.region(renderer.as_ref(), spec, opts.scale)?;
let fallback = spec.embedded.and_then(|index| pictures.svg_png(index));
Some((data, format, fallback))
},
);
let mut media = Media::default();
let content = fill_images(&body.xml, &body.images, drawn, &mut media);
let links: Vec<(String, String)> = body
.links
.iter()
.enumerate()
.map(|(i, url)| (format!("rIdLink{i}"), url.clone()))
.collect();
let document = format!("{XML_DECL}<w:document {DOCUMENT_NAMESPACES}><w:body>{content}</w:body></w:document>");
let mut content_types = format!("{XML_DECL}{CONTENT_TYPES}");
let mut rels = document_rels(&media.rels, &links);
if !body.notes.is_empty() {
content_types = content_types.replace("</Types>", &format!("{FOOTNOTES_TYPE}</Types>"));
rels = rels.replace("</Relationships>", &format!("{FOOTNOTES_REL}</Relationships>"));
}
let mut zip = ZipWriter::default();
let mut text = |name: &str, data: &str| zip.add(name, data.as_bytes(), Compression::Deflated);
if media.has_svg() {
content_types = content_types.replacen(
"<Override",
"<Default Extension=\"svg\" ContentType=\"image/svg+xml\"/><Override",
1,
);
}
text("[Content_Types].xml", &content_types);
text("_rels/.rels", &format!("{XML_DECL}{PACKAGE_RELS}"));
text(
"docProps/core.xml",
&core_props(&doc_title(doc), &doc.meta, crate::render::source_label(doc)),
);
text("docProps/app.xml", &format!("{XML_DECL}{APP_PROPS}"));
text("word/document.xml", &document);
text("word/styles.xml", &format!("{XML_DECL}{STYLES}"));
text("word/settings.xml", &format!("{XML_DECL}{SETTINGS}"));
text("word/_rels/document.xml.rels", &rels);
if !body.notes.is_empty() {
text("word/footnotes.xml", &footnotes_xml(&body.notes));
}
for (name, data) in &media.files {
zip.add(name, data, Compression::Stored);
}
(zip.finish(), media)
}
fn fill_images(xml: &str, images: &[PendingImage], drawn: Vec<Option<DrawnPicture>>, media: &mut Media) -> String {
let mut drawn = drawn;
let mut out = String::with_capacity(xml.len());
let mut rest = xml;
while let Some(start) = rest.find(MARK) {
out.push_str(&rest[..start]);
let after = &rest[start + MARK.len_utf8()..];
let end = after.find(MARK).expect("placeholders are closed");
let index: usize = after[..end].parse().expect("placeholder index");
if let Some((data, format, fallback)) = drawn[index].take() {
let (id, svg_id) = match format {
PictureFormat::Svg => match fallback {
Some(png) => {
let id = media.add(png.to_vec(), "png");
let svg_id = media.add(data, "svg");
(id, Some(svg_id))
}
None => (media.add(data, "svg"), None),
},
PictureFormat::Jpeg => (media.add(data, "jpeg"), None),
PictureFormat::Png => (media.add(data, "png"), None),
};
media.shown.push((media.files.len() - 1, images[index].hint));
let number = media.shown.len();
out.push_str(&drawing_xml(number, &id, svg_id.as_deref(), &images[index]));
}
rest = &after[end + MARK.len_utf8()..];
}
out.push_str(rest);
out
}
fn drawing_xml(number: usize, rel_id: &str, svg_id: Option<&str>, image: &PendingImage) -> String {
let (cx, cy) = (image.width_emu, image.height_emu);
let blip = match svg_id {
Some(svg_id) => format!(
"<a:blip r:embed=\"{rel_id}\"><a:extLst><a:ext uri=\"{SVG_BLIP_EXT}\">\
<asvg:svgBlip xmlns:asvg=\"{SVG_BLIP_NS}\" r:embed=\"{svg_id}\"/></a:ext></a:extLst></a:blip>"
),
None => format!("<a:blip r:embed=\"{rel_id}\"/>"),
};
format!(
"<w:r><w:drawing><wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\"><wp:extent cx=\"{cx}\" cy=\"{cy}\"/>\
<wp:docPr id=\"{number}\" name=\"Picture {number}\" descr=\"{alt}\"/>\
<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect=\"1\"/></wp:cNvGraphicFramePr>\
<a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"><pic:pic>\
<pic:nvPicPr><pic:cNvPr id=\"{number}\" name=\"image{number}\"/><pic:cNvPicPr/></pic:nvPicPr>\
<pic:blipFill>{blip}<a:stretch><a:fillRect/></a:stretch></pic:blipFill>\
<pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{cx}\" cy=\"{cy}\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></pic:spPr>\
</pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>",
alt = xml::esc(&image.alt)
)
}