1use quick_xml::Writer;
2use quick_xml::events::{BytesDecl, BytesEnd, BytesStart, BytesText, Event};
3use reqwest::Client;
4use std::collections::HashMap;
5use std::fs::File;
6use std::io::{Cursor, Read, Write};
7use std::path::Path;
8use std::time::Duration;
9use thiserror::Error;
10use uuid::Uuid;
11use zip::write::SimpleFileOptions;
12use zip::{ZipArchive, ZipWriter};
13
14pub struct DocxTemplate {
15 text_replacements: HashMap<String, String>,
17 image_replacements: HashMap<String, Option<DocxImage>>,
19 client: Client,
21}
22
23impl DocxTemplate {
24 pub fn new() -> Self {
25 DocxTemplate {
26 text_replacements: HashMap::new(),
27 image_replacements: HashMap::new(),
28 client: Client::builder()
29 .timeout(Duration::from_secs(10)) .build()
31 .unwrap(),
32 }
33 }
34
35 pub fn add_text_replacement(&mut self, placeholder: &str, value: &str) {
39 self.text_replacements
40 .insert(placeholder.to_string(), value.to_string());
41 }
42
43 pub fn add_image_replacement(
47 &mut self,
48 placeholder: &str,
49 image_path: Option<&str>,
50 ) -> Result<(), DocxError> {
51 match image_path {
52 None => {
53 self.image_replacements
55 .insert(placeholder.to_string(), None);
56 }
57 Some(data) => {
58 self.image_replacements
60 .insert(placeholder.to_string(), Some(DocxImage::new(data)?));
61 }
62 }
63
64 Ok(())
65 }
66 pub fn add_image_size_replacement(
72 &mut self,
73 placeholder: &str,
74 image_path: Option<&str>,
75 width: f32,
76 height: f32,
77 ) -> Result<(), DocxError> {
78 match image_path {
79 None => {
80 self.image_replacements
82 .insert(placeholder.to_string(), None);
83 }
84 Some(file_path) => {
85 self.image_replacements.insert(
87 placeholder.to_string(),
88 Some(DocxImage::new_size(file_path, width, height)?),
89 );
90 }
91 }
92
93 Ok(())
94 }
95
96 pub async fn add_image_url_replacement(
100 &mut self,
101 placeholder: &str,
102 image_url: Option<&str>,
103 ) -> Result<(), DocxError> {
104 match image_url {
105 None => {
106 self.image_replacements
108 .insert(placeholder.to_string(), None);
109 }
110 Some(url) => {
111 let response = self.client.get(url).send().await?;
113 if response.status().is_success() {
115 let image_data = response.bytes().await?.to_vec();
117 self.image_replacements.insert(
119 placeholder.to_string(),
120 Some(DocxImage::new_image_data(url, image_data)?),
121 );
122 }
123 }
124 }
125
126 Ok(())
127 }
128
129 pub async fn add_image_size_url_replacement(
135 &mut self,
136 placeholder: &str,
137 image_url: Option<&str>,
138 width: f32,
139 height: f32,
140 ) -> Result<(), DocxError> {
141 match image_url {
142 None => {
143 self.image_replacements
145 .insert(placeholder.to_string(), None);
146 }
147 Some(url) => {
148 let response = self.client.get(url).send().await?;
150 if response.status().is_success() {
152 let image_data = response.bytes().await?.to_vec();
154 self.image_replacements.insert(
156 placeholder.to_string(),
157 Some(DocxImage::new_image_data_size(
158 url, image_data, width, height,
159 )?),
160 );
161 }
162 }
163 }
164
165 Ok(())
166 }
167
168 pub fn process_template(
172 &self,
173 template_path: &str,
174 output_path: &str,
175 ) -> Result<(), DocxError> {
176 let template_file = File::open(template_path)?;
178 let mut archive = ZipArchive::new(template_file)?;
179
180 let output_file = File::create(output_path)?;
182 let mut zip_writer = ZipWriter::new(output_file);
183
184 for i in 0..archive.len() {
186 let mut file = archive.by_index(i)?;
187 let mut contents = Vec::new();
189 file.read_to_end(&mut contents)?;
191 match file.name() {
193 "word/document.xml" => {
194 contents = self.process_document_xml(&contents)?;
196 }
197 "word/_rels/document.xml.rels" => {
198 contents = self.process_rels_xml(&contents)?;
200 }
201 &_ => {}
202 }
203
204 let option = SimpleFileOptions::default()
206 .compression_method(file.compression())
207 .unix_permissions(file.unix_mode().unwrap_or(0o644));
208 zip_writer.start_file(file.name(), option)?;
210 zip_writer.write_all(&contents)?;
211 }
212
213 for (_, replacement) in &self.image_replacements {
215 if let Some(replacement) = replacement {
216 let image_path = format!(
217 "word/media/image_{}.{}",
218 replacement.relation_id,
219 DocxTemplate::get_extension(&replacement.image_path)?
220 );
221 zip_writer.start_file(&image_path, SimpleFileOptions::default())?;
223 zip_writer.write_all(&replacement.image_data)?;
224 }
225 }
226 zip_writer.finish()?;
228 Ok(())
229 }
230
231 fn process_element(&self, _element: &mut BytesStart) -> Result<(), DocxError> {
232 Ok(())
234 }
235
236 fn process_document_xml(&self, contents: &[u8]) -> Result<Vec<u8>, DocxError> {
239 let mut xml_writer = Writer::new(Cursor::new(Vec::new()));
241 let mut reader = quick_xml::Reader::from_reader(&contents[..]);
245 let mut buf = Vec::new();
247 let mut current_placeholder = String::new();
249 loop {
251 match reader.read_event_into(&mut buf)? {
253 Event::Start(e) => {
254 let mut element = e.to_owned();
255 self.process_element(&mut element)?;
256 if e.name().as_ref() == b"w:p" {
257 current_placeholder.clear();
258 }
259 xml_writer.write_event(Event::Start(element))?;
260 }
261 Event::Text(e) => {
262 let mut text = e.unescape()?.into_owned();
264 self.process_text(&mut text);
266 if self.image_replacements.contains_key(&text) {
268 current_placeholder.push_str(&text);
269 } else {
270 xml_writer.write_event(Event::Text(BytesText::new(text.as_str())))?;
271 }
272 }
273 Event::End(e) => {
274 if e.name().as_ref() == b"w:p" && !current_placeholder.is_empty() {
276 if let Some(Some(docx_image)) =
277 self.image_replacements.get(¤t_placeholder)
278 {
279 DocxTemplate::create_drawing_element(
281 &mut xml_writer,
282 &docx_image.relation_id,
283 docx_image.width,
284 docx_image.height,
285 )?;
286 } else {
287 xml_writer.write_event(Event::Text(BytesText::from_escaped(
289 "",
291 )))?;
292 }
293 current_placeholder.clear();
294 }
295 xml_writer.write_event(Event::End(e))?;
296 }
297 Event::Eof => break,
298 e => {
299 xml_writer.write_event(e)?
301 }
302 }
303 buf.clear();
304 }
305 Ok(xml_writer.into_inner().into_inner())
307 }
308
309 fn process_rels_xml(&self, xml_data: &[u8]) -> Result<Vec<u8>, DocxError> {
310 let mut writer = Writer::new(Cursor::new(Vec::new()));
312 writer.write_event(Event::Decl(BytesDecl::new(
314 "1.0",
315 Some("UTF-8"),
316 Some("yes"),
317 )))?;
318
319 writer.write_event(Event::Start(
321 BytesStart::new("Relationships").with_attributes([(
322 "xmlns",
323 "http://schemas.openxmlformats.org/package/2006/relationships",
324 )]),
325 ))?;
326
327 let mut reader = quick_xml::Reader::from_reader(xml_data);
329 let mut buf = Vec::new();
330
331 loop {
332 match reader.read_event_into(&mut buf)? {
334 Event::Empty(e) if e.name().as_ref() == b"Relationship" => {
336 writer.write_event(Event::Empty(e))?;
338 }
339 Event::Eof => break,
341 _ => {}
342 }
343 buf.clear();
345 }
346
347 for (_, value) in &self.image_replacements {
349 if let Some(docx_image) = value {
350 let extension = DocxTemplate::get_extension(&docx_image.image_path)?;
352 let image_path = format!("media/image_{}.{}", docx_image.relation_id, extension);
354 let relationship = BytesStart::new("Relationship").with_attributes([
356 ("Id", docx_image.relation_id.as_str()),
357 (
358 "Type",
359 "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
360 ),
361 ("Target", &image_path),
362 ]);
363 writer.write_event(Event::Empty(relationship))?;
365 }
366 }
367
368 writer.write_event(Event::End(BytesEnd::new("Relationships")))?;
370 Ok(writer.into_inner().into_inner())
372 }
373
374 fn get_extension(image_path: &str) -> Result<&str, DocxError> {
375 Path::new(image_path)
376 .extension()
377 .and_then(|s| s.to_str())
378 .ok_or_else(|| {
379 DocxError::ImageNotFound("Could not determine image extension".to_string())
380 })
381 }
382 fn process_text(&self, text: &mut String) {
384 for (placeholder, value) in &self.text_replacements {
385 *text = text.replace(placeholder, value);
386 }
387 }
388
389 fn create_drawing_element<T>(
390 writer: &mut Writer<T>,
391 relation_id: &str,
392 width: u64,
393 height: u64,
394 ) -> Result<(), DocxError>
395 where
396 T: Write,
397 {
398 let drawing = format!(
399 r#"
400 <w:drawing>
401 <wp:inline distT="0" distB="0" distL="0" distR="0">
402 <wp:extent cx="{}" cy="{}"/>
403 <wp:docPr id="1" name="Picture 1" descr="Generated image"/>
404 <wp:cNvGraphicFramePr>
405 <a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/>
406 </wp:cNvGraphicFramePr>
407 <a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
408 <a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
409 <pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
410 <pic:nvPicPr>
411 <pic:cNvPr id="0" name="Picture 1" descr="Generated image"/>
412 <pic:cNvPicPr><a:picLocks noChangeAspect="1"/></pic:cNvPicPr>
413 </pic:nvPicPr>
414 <pic:blipFill>
415 <a:blip r:embed="{}"/>
416 <a:stretch>
417 <a:fillRect/>
418 </a:stretch>
419 </pic:blipFill>
420 <pic:spPr>
421 <a:xfrm>
422 <a:off x="0" y="0"/>
423 <a:ext cx="{}" cy="{}"/>
424 </a:xfrm>
425 <a:prstGeom prst="rect">
426 <a:avLst/>
427 </a:prstGeom>
428 </pic:spPr>
429 </pic:pic>
430 </a:graphicData>
431 </a:graphic>
432 </wp:inline>
433 </w:drawing>
434 "#,
435 width, height, relation_id, width, height,
436 );
437
438 let mut reader = quick_xml::Reader::from_str(&drawing);
439 reader.config_mut().trim_text(true);
440 let mut buf = Vec::new();
441
442 loop {
443 match reader.read_event_into(&mut buf)? {
444 Event::Eof => break,
445 e => {
446 writer.write_event(e)?;
447 }
448 }
449 }
450 Ok(())
451 }
452}
453
454struct DocxImage {
456 pub image_path: String,
458 pub image_data: Vec<u8>,
460 pub relation_id: String,
462 pub width: u64,
464 pub height: u64,
466}
467
468impl DocxImage {
469 pub fn new(image_path: &str) -> Result<Self, DocxError> {
472 Self::new_size(image_path, 6.09, 5.9)
473 }
474 pub fn new_size(image_path: &str, width: f32, height: f32) -> Result<Self, DocxError> {
479 let mut file = File::open(image_path)?;
481 let mut image_data = Vec::new();
482 file.read_to_end(&mut image_data)?;
483 DocxImage::new_image_data_size(image_path, image_data, width, height)
484 }
485
486 pub fn new_image_data(image_url: &str, image_data: Vec<u8>) -> Result<Self, DocxError> {
490 DocxImage::new_image_data_size(image_url, image_data, 6.09, 5.9)
491 }
492
493 pub fn new_image_data_size(
499 image_url: &str,
500 image_data: Vec<u8>,
501 width: f32,
502 height: f32,
503 ) -> Result<Self, DocxError> {
504 Ok(DocxImage {
505 image_path: image_url.to_string(),
506 relation_id: format!("rId{}", Uuid::new_v4().simple()),
507 width: (width * 360000.0) as u64,
508 height: (height * 360000.0) as u64,
509 image_data,
510 })
511 }
512}
513
514#[derive(Error, Debug)]
515pub enum DocxError {
516 #[error("IO error: {0}")]
517 Io(#[from] std::io::Error),
518 #[error("Zip error: {0}")]
519 Zip(#[from] zip::result::ZipError),
520 #[error("XML error: {0}")]
521 Xml(#[from] quick_xml::Error),
522 #[error("UTF-8 error: {0}")]
523 Utf8(#[from] std::string::FromUtf8Error),
524 #[error("Image not found: {0}")]
525 ImageNotFound(String),
526 #[error("Image url not found: {0}")]
527 ImageUrlFound(#[from] reqwest::Error),
528}