0
votes

Context

I need to produce Microsoft Word compatible docx files containing some tables in a Web application running on a Linux system. After some research I found that it was possible to prepare en empty document containing all the required styles (for paragraphs, characters and tables) in Microsoft word and then fill it with docx4j.

It really works fine for paragraphs: I just have to extract the style from its name, and extract the pPr attribute from the style:

P p = factory.createP();                 // create an empty paragraph
String styleId = wpMLPackage.getMainDocumentPart().getStyleDefinitionsPart()
            .getIDForStyleName(styleName);    // find the styleID because the template has defined names
PPr ppr = wpMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getStyleById(styleId)
            .getPPr();                        // extract the PPr from the style
p.setPPr(ppr);                                // and affect it to the paragraph
}
R r = factory.createR();                 // finally set the paragraph text
Text txt = factory.createText();
txt.setValue(text);
r.getContent().add(txt);
p.getContent().add(r);

The convenience method wpMLPackage.getMainDocumentPart().addStyledParagraphOfText(styleId, text); works the same only requiring to find the styleID

Problem

When it comes to table styles, that cannot be used because tbl.setTblPr(tblPr) expects a TblPr object, while style.getTblPr returns a CTTblPrBase which cannot be cast to a TblPr, and I could not find a way to extract a TblPr from a table style.

Question

How is it possible to create a table from docx4j and affect it a (table) style already present in the document?

1

1 Answers

1
votes

Table styles are affected in a quite different way.

In fact, we do not extract the table property from the style but create a different object which is a TblStyle.

The code is as simple as:

    tbl = factory.createTbl();                   // create an empty table
    TblPr tblPr = factory.createTblPr();         // create a brand new TblPr
    TblStyle tblStyle = new TblStyle();          // create a brand new TblStyle
    String styleID = wpMLPackage.getMainDocumentPart().getStyleDefinitionsPart()
            .getIDForStyleName(styleName));      // find the style ID from the name
    tblStyle.setVal(styleID);                    // just tell tblStyle what style it shall be
    tblPr.setTblStyle(tblStyle);                 // and affect each object its property...
    this.tbl.setTblPr(tblPr);
    wpMLPackage.getMainDocumentPart().getContent().add(tbl);   // we can now add the styled table