use std::collections::HashMap;
use serde_json::{to_string, Value};
use crate::utils::*;
pub struct DOCX {
pub content: HashMap<String, String>,
pub file_name: String,
pub placeholders: HashMap<String, Value>,
pub placeholders_blocks: HashMap<String, String>,
pub placeholder_images: HashMap<String, String>,
}
impl DOCX {
pub fn new(file_name: String) -> DOCX {
DOCX {
file_name,
content: HashMap::new(),
placeholders: HashMap::new(),
placeholders_blocks: HashMap::new(),
placeholder_images: HashMap::new(),
}
}
pub fn read(&mut self) {
self.content = read_raw_docx(&self.file_name);
}
pub fn add_placeholder<T>(&mut self, placeholder: &str, replaced_content: T) where Value: From<T> {
self.placeholders.insert(placeholder.to_string(), Value::from(replaced_content));
}
pub fn add_placeholders_from_json(&mut self, placeholders_content: &str) {
let v: Value = serde_json::from_str(placeholders_content).unwrap();
if let Value::Object(map) = v {
process_json_map(self,"", &map);
}
}
pub fn add_image_placeholder(&mut self, placeholder: &str, image: &str) {
let media_dir = "word/media/";
self.placeholder_images.insert(format!("{}{}", media_dir, placeholder.to_string()), image.to_string());
}
pub fn remove_image_placeholder(&mut self, placeholder: &str) {
let media_dir = "word/media/";
self.placeholder_images.remove(&format!("{}{}", media_dir, placeholder));
}
pub fn init_placeholders(&mut self) {
let mut new_content = HashMap::new();
self.placeholders = add_placeholder_helpers(&mut self.placeholders);
let rendered = init_each_placeholders(self.content["word/document.xml"].clone(), &mut self.placeholders, false);
self.content.remove("word/document.xml");
self.content.insert("word/document.xml".to_string(), rendered);
for (k, v) in &self.content {
new_content.insert(k.to_string(), init_placeholders(&mut self.placeholders, v));
}
self.content = new_content;
}
pub fn save(&self, output: &str) {
let result = render_docx(&self);
std::fs::write(output, result).unwrap();
}
pub fn render(&self) -> Vec<u8> {
render_docx(&self)
}
}