3

I'm having problem creating a Paragraph with docx4j. Well, actually not the paragraph itself, but it's contents. I'm putting together a new document from paragraphs (actually "blocks" made of paragraphs) and everything is working fine. I'm appending them to a list, and when all needed paragraphs are there, I assemble the document. Now, between these blocks, I need new paragraphs, with custom text added. I'm using this function to create the paragraph:

private P createParagraph(String content) {

P result = factory.createP();
R run = factory.createR();
Text text = factory.createText();

text.setValue(content);
run.getContent().add(text);
result.getContent().add(run);

System.out.println("HEADER : " + result.toString());

return result;
}

The print only prints "HEADER : ", the result.toString() is an empty string. Why is that?

BONUS question : I did not want to open a new thread for this. Is it possible, to add an id for a paragraph, which will appear in the generated html? (like p id="xyz" ...>

Thank you very much!

omniflash
  • 191
  • 1
  • 14
  • For your ID question, please see my answer at http://stackoverflow.com/questions/18255776/open-xml-add-custom-not-visible-data-to-paragraph-table/18262734#18262734 If you have a followup question on paragraph ids, please post it as a separate question. – JasonPlutext Sep 05 '13 at 23:21

1 Answers1

2

If you want to see the XML your P object will become, use:

    System.out.println(
            XmlUtils.marshaltoString(result, true, true) );

org.docx4j.wml.P is a class generated by JAXB's xjc.

There are a couple of plugins listed at https://java.net/projects/jaxb2-commons/pages/Home which we could have used to generate a toString method, but we didn't.

If you want the text content of the paragraph, you can use TextUtils

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
JasonPlutext
  • 15,352
  • 4
  • 44
  • 84
  • Thank you. I now created a blank document, with only the text I want in the paragraph. Using the method you mentioned I checked the structure. I added all the missing tags, and now it looks exactly the same as my document viewed in the docx4j webapp. The only difference is a lot of namespace definitions in my starting element: – omniflash Sep 05 '13 at 15:10
  • I've updated my answer. Regarding namespaces, these would generally be declared once at the top of the part (as opposed to on each paragraph). JAXB will take care of that. The Sun/Oracle implementation doesn't remove redundant ones, though. – JasonPlutext Sep 05 '13 at 23:22