I am getting a similar error when I am trying to add a table to the contents of the mainDocumentPart at a specific index, using below code
wordMLPackage.getMainDocumentPart().getContent().add(5, tbl);
However, it is working perfectly fine if I add it directly to the mainDocumentPart
wordMLPackage.getMainDocumentPart().addObject(tbl);
Getting error while generating the output file using
Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
Code to create table is
Tbl tbl = Context.getWmlObjectFactory().createTbl();
// // ///////////////////
String strTblPr = "<w:tblPr " + Namespaces.W_NAMESPACE_DECLARATION + ">" + "<w:tblStyle w:val=\"TableGrid\"/>"
+ "<w:tblW w:w=\"0\" w:type=\"auto\"/>" + "<w:tblLook w:val=\"04A0\"/>" + "</w:tblPr>";
TblPr tblPr = null;
try {
tblPr = (TblPr) XmlUtils.unmarshalString(strTblPr);
}
catch (JAXBException e) {
// Shouldn't happen
e.printStackTrace();
}
tbl.setTblPr(tblPr);
TblGrid tblGrid = Context.getWmlObjectFactory().createTblGrid();
tbl.setTblGrid(tblGrid);
int writableWidthTwips1 = wordMLPackage.getDocumentModel().getSections().get(0).getPageDimensions()
.getWritableWidthTwips();
int cellWidthTwips1 = new Double(Math.floor((writableWidthTwips / cols))).intValue();
for (int i = 0; i < cols; i++) {
TblGridCol gridCol = Context.getWmlObjectFactory().createTblGridCol();
gridCol.setW(BigInteger.valueOf(cellWidthTwips));
tblGrid.getGridCol().add(gridCol);
}
List<String> ls = new ArrayList<String>();
ls.add("monika");
ls.add("abc");
ls.add("hi");
ls.add("hello");
ls.add("Byee");
Tc tc = null;
Tr tr = null;
int rows = 3;
for (int j = 0; j < rows; j++) {
tr = Context.getWmlObjectFactory().createTr();
for (int i = 0; i < cols; i++) {
tc = Context.getWmlObjectFactory().createTc();
TcPr tcPr = Context.getWmlObjectFactory().createTcPr();
tc.setTcPr(tcPr);
TblWidth cellWidth = Context.getWmlObjectFactory().createTblWidth();
tcPr.setTcW(cellWidth);
cellWidth.setType("dxa");
cellWidth.setW(BigInteger.valueOf(cellWidthTwips));
org.docx4j.wml.P p1 = factory.createP();
org.docx4j.wml.Text t1 = factory.createText();
t1.setValue(ls.get(i));
org.docx4j.wml.R run1 = factory.createR();
run1.getContent().add(t1);
p1.getContent().add(run1);
tc.getContent().add(p1);
tr.getContent().add(tc);
}
tbl.getContent().add(tr);
}
Can someone please tell me what am I missing here