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

Add page number to footer #611

Open arifd opened 1 year ago

arifd commented 1 year ago

Hey thanks for this wonderful little library!

I'm trying to add a page number in the footer of every page, but I'm not able to figure out how to do it.

Using the footer example, I thought maybe just set has_numbering to true, but it doesn't appear to do anything

use docx_rs::*;

pub fn main() -> Result<(), DocxError> {
    let path = std::path::Path::new("footer.docx");
    let file = std::fs::File::create(&path).unwrap();
    let mut footer = Footer::new();
    footer.has_numbering = true;
    footer = footer.add_paragraph(Paragraph::new().add_run(Run::new().add_text("Hello")));
    Docx::new()
        .footer(footer)
        .add_paragraph(Paragraph::new().add_run(Run::new().add_text("World")))
        .build()
        .pack(file)?;
    Ok(())
}

If there is no handy API to do it directly yet, this stackoverflow post does describe a way it could be added manually, and I see docx-rs does offer some level of xml manipulation via functions like Docx::add_custom_item and Docx::custom_property but I don't understand the docx format well enough to implement this.

Could you advise?

Thanks in advance!!

nikitavbv commented 8 months ago

For anyone interested, here is a workaround that can be used here:

Docx::new().footer(
        Footer::new().add_paragraph(
            Paragraph::new().add_run(
                Run::new()
                    .add_field_char(FieldCharType::Begin, false)
                    .add_instr_text(InstrText::Unsupported("PAGE".to_owned()))
                    .add_field_char(FieldCharType::End, false),
            )
        )
    );

(based on the approach from the StackOverflow link from above)