Page 1 of 1
Inserting into existing document
Posted:
Thu Feb 03, 2011 10:26 pm
by pandaadb
Hi,
I have this scenario: I use a template document for the first 7 pages of my document, because they are generally always the same. After that, I add about 400 pages of produced formatted output to the document. This all works very nice with docX4J - thanks for that.
Now I need to add something to the template document. The 3rd page is reserved for statistical data, so I somehow need to get to that point programmatically and insert a table there that I generate at runtime.
How can I navigate to that part of the page using docx4J and insert there?
kind regards,
Artur
Re: Inserting into existing document
Posted:
Fri Feb 04, 2011 11:50 am
by davebrown
Hi Artur,
If you know the text of the paragraph preceding the place where you want to put the table, the following code will do it:
- Code: Select all
void insertTable(WordprocessingMLPackage pkg, String afterText, Tbl table)
throws Exception {
Body b = pkg.getMainDocumentPart().getJaxbElement().getBody();
int addPoint = -1, count = 0;
for (Object o : b.getEGBlockLevelElts()) {
if (o instanceof P && getElementText(o).startsWith(afterText)) {
addPoint = count + 1;
break;
}
count++;
}
if (addPoint != -1)
b.getEGBlockLevelElts().add(addPoint, table);
else {
// didn't find paragraph to insert after...
}
}
String getElementText(Object jaxbElem) throws Exception {
StringWriter sw = new StringWriter();
TextUtils.extractText(jaxbElem, sw);
return sw.toString();
}
Basically, a table can be a peer/sibling of paragraph as a child of body. Note the little utility method getElementText() to extract the text from a paragraph without formatting. My calling code looks like this:
- Code: Select all
WordprocessingMLPackage pkg = WordprocessingMLPackage.load(new File("/tmp/template.docx"));
Tbl table = TblFactory.createTable(3, 3, 100);
insertTable(pkg, "Now here is a table", table);
pkg.save(new File("/tmp/filled-template.docx"));
Hope that helps,
dave
Re: Inserting into existing document
Posted:
Fri Feb 11, 2011 3:29 am
by pandaadb
Thanks for your answer. I fixed it in a similar way. Since the start of my document is a template file I created, the insertion must be at the same position every time. I just hoped there might be a less hardcoded way for me to find that place. But I think looking for a String or something specific there is probably the only way to find that.
I thought maybe there is a method that inserts at a specific position, like "insertTableAtPage( int pagenumber)" or something similar to that, so I could put that thing always on page 3 for example.
Cheers!
-- Artur
Re: Inserting into existing document
Posted:
Thu Jan 19, 2012 2:16 am
by sureshbabubv
Hi pandaadb,
Can you please share your code.
Thanks & Regards,
B.V.Suresh Babu.