Page 1 of 1

How to Replace variable in Header

PostPosted: Sun Aug 28, 2022 4:41 pm
by swilliams7996
This code is not working for me. I'm trying to replace a variable in my header. I need help.

public void header() throws Exception{

File doc = new File("C:/Users/Stacy/Documents/Thermal LESS.docx");

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(doc);

VariablePrepare.prepare(wordMLPackage);

HashMap<String, String> header = new HashMap<>();

header.put("LESS-Thermal-201908 ", "Stacy Header");

//headerPart.getDefaultHeader().getContent().add(header);

HashMap<String, String> footer = new HashMap<>();

footer.put(" ", "footer");

for (SectionWrapper section : wordMLPackage.getDocumentModel().getSections()) {

if (section.getHeaderFooterPolicy() != null) {

section.getHeaderFooterPolicy().getDefaultHeader().variableReplace(header);
section.getHeaderFooterPolicy().getDefaultFooter().variableReplace(footer);
wordMLPackage.save((new java.io.File("C:/Users/Stacy/Documents/Thermal LESSHeader.docx")));

}

}

}

Re: How to Replace variable in Header

PostPosted: Mon Aug 29, 2022 7:11 am
by jason
Hard to say without seeing your docx, but perhaps your variable is split into separate runs by spelling/grammar correction, or formatting? To start with, try a simple word in place of LESS-Thermal-201908, for example ${ball}

Or your docx is not using the default header (for example, a single page with a first page header).

Re: How to Replace variable in Header

PostPosted: Mon Aug 29, 2022 2:14 pm
by swilliams7996
Can you give me an example of default header, I'm new to Docx4j. What's in my code is wrong? Show me an example of how I can replace a variable in the header.

Re: How to Replace variable in Header

PostPosted: Tue Aug 30, 2022 7:06 am
by jason
http://webapp.docx4java.org/OnlineDemo/ ... rence.html

feel free to email me your docx. Or you can anonymise it using https://github.com/plutext/docx4j/blob/ ... ingle.java then attach it.

Re: How to Replace variable in Header

PostPosted: Fri Sep 02, 2022 3:10 pm
by swilliams7996
I want to change variable in my header and it's the same header on all ten of my file. How can I replace a variable? I thought I could do it like I did the main document but that's not working. Can someone show me an example?