I noticed some interesting behaviour when it comes to adding HTML to a table cell (via TraversalUtil or XPath). More concrete, I replace a placeholder by some formatted text coming from a DB. What I noticed now is that if the placeholder is a single <w:p> in a table cell, the code will run fine, but the document won't open (i.e. error message saying that the document structure got corrupted). However, if I add an empty paragraph to the template right before my placeholder text (I have two paragraphs in the table cell now), the code will not only run through and I can open the document and have the expected result, although there is now the addional paragraph, that I must delete manually.
My conclusion is that, there seems to be a problem when replacing a paragraph within a table cell with some formatted text (HTML) when there is no sibling paragraph in the very same cell.
Has anyone of you made the same experience and maybe found a solution or a work arround?
Please find my code below:
- Code: Select all
//Replace Placeholders with HTML
//This method is called whenever an HTML placeholder is found while traversing over the template document
private void replaceHTML(P p, String placeholderValue, Properties templateProperties){
//index = -1 if the paragraph is in a table cell
int index = givenPackage.getMainDocumentPart().getContent().indexOf(p);
try{
//Retrieves a formatted text from a database
placeholderValue = replacePlaceholdersByValue(placeholderValue, templateProperties);
//Create HTML
String html = "<html>" + placeholderValue + "</html>";
AlternativeFormatInputPart afiPart = null;
logger.info("Trying to create an html part.");
afiPart = new AlternativeFormatInputPart(new PartName("/hw" + String.valueOf(htmlCounter) + ".html")); //CAUTION: each html part needs a new name!!
htmlCounter++;
//Parse Content
logger.info("Get the Bytes and set the Content type of the html part.");
afiPart.setBinaryData(html.getBytes("UTF-8"));
afiPart.setContentType(new ContentType("text/html"));
Relationship altChunkRel = null;
logger.info("adding the Target Path...");
altChunkRel = givenPackage.getMainDocumentPart().addTargetPart(afiPart);
//Add HTML to document
logger.info("Adding HTML to the document..");
CTAltChunk ac = Context.getWmlObjectFactory().createCTAltChunk();
ac.setId(altChunkRel.getId());
//Paragraph in a table cell
if (p.getParent() instanceof org.docx4j.wml.Tc){
Tc parent = (Tc) p.getParent();
int subIndex = parent.getContent().indexOf(p);
parent.getContent().set(subIndex,ac);
//Regular paragraph
}else if (p.getParent() instanceof org.docx4j.wml.Body){
logger.debug("ersetze html part an der Stelle "+index);
givenPackage.getMainDocumentPart().getContent().set(index,ac);
}else{
logger.error("Parent object class could not be processed");
}
}catch(Exception e){
e.printStackTrace();
}
}