bokuweb / docx-rs

:memo: A .docx file writer with Rust/WebAssembly.
https://bokuweb.github.io/docx-rs/
MIT License
341 stars 59 forks source link

Adding images to first_header not working #749

Open Tadeus12 opened 1 month ago

Tadeus12 commented 1 month ago

Describe the bug

I can add an image as shown in the code to the header or footer but not to first_header or first_footer, also even_header is not working either. adding text works fine but images can't be shown.

I am creating my image like this:

use docx_rs::*;
use std::io::Cursor;
use std::sync::atomic::{AtomicUsize, Ordering};
use wasm_bindgen::prelude::{wasm_bindgen, JsValue};
use serde_json::Value;
use serde_wasm_bindgen::from_value;
pub fn pic(image: Vec<u8>, w_px: u32, h_px: u32) -> Pic {
    Pic {
        id: create_pic_rid(generate_pic_id()),
        image,
        size: (px_to_emu(w_px), px_to_emu(h_px)),
        position_type: DrawingPositionType::Anchor,
        simple_pos: false,
        simple_pos_x: 0,
        simple_pos_y: 0,
        layout_in_cell: false,
        relative_height: 190500,
        allow_overlap: true,
        position_v: DrawingPosition::Offset(0),
        position_h: DrawingPosition::Offset(0),
        relative_from_h: RelativeFromHType::LeftMargin,
        relative_from_v: RelativeFromVType::TopMargin,
        dist_t: 0,
        dist_b: 0,
        dist_l: 0,
        dist_r: 0,
        rot: 0,
    }
}
fn px_to_emu(px: u32) -> u32 {
    px * 9525
}
fn generate_pic_id() -> usize {
    static PIC_ID: AtomicUsize = AtomicUsize::new(1);
    PIC_ID.fetch_add(1, Ordering::Relaxed)
}
fn create_pic_rid(id: usize) -> String {
    format!("rIdImage{}", id)
}
#[wasm_bindgen]
pub fn rust_create_docx(content: JsValue, image_data: &[u8]) -> Result<Vec<u8>, JsValue> {
 let pic = pic(image_data.to_vec(), 744, 1052);

 let header = Header::new().add_paragraph(Paragraph::new().add_run(Run::new().add_image(pic)));

 // this is not working:
 let mut docx = Docx::new().first_header(header);

 // this works fine:
 let mut docx = Docx::new().header(header);

 let mut buffer = Cursor::new(Vec::new());
 docx.build()
        .pack(&mut buffer)
        .map_err(|e| JsValue::from_str(&e.to_string()))?;
    Ok(buffer.into_inner())
}

Screenshots

bug

Desktop