Search code examples
javadocx4j

docx4j adding style to paragraph destroys document


I'm trying to add a paragraph containing a headline (with style) and some plain unformatted text. The following code destroys the document.

Edit: After executing the following code and trying to open the document in word I get an error message "Unspecified Error" Location: Part /word/document.xml Line 1 Column 0

        ObjectFactory factory = new ObjectFactory();
        P complete = factory.createP();

        org.docx4j.wml.P headline=factory.createP();
        R hrun = factory.createR();
        Text htxt = new Text();
        hrun.getContent().add(htxt);
        htxt.setValue(View_Beta.this.falseAlarmChoice.getSelectedItem().toString());

        headline.getContent().add(hrun);        



    org.docx4j.wml.PPr  pPr = factory.createPPr();
        headline.setPPr(pPr);
        org.docx4j.wml.PPrBase.PStyle pStyle = factory.createPPrBasePStyle();
        pPr.setPStyle(pStyle);
        pStyle.setVal("Title"); 
        complete.getContent().add(headline);

        P ptext = factory.createP();
        R rtext = factory.createR();
        Text ttext = new Text();
        rtext.getContent().add(ttext);
        ptext.getContent().add(rtext);

        ttext.setValue(falseAlarmChoice.getSelectedItem()
                + falseAlarmDsc.getText());
        complete.getContent().add(ptext);

        //add to document context
        View_Beta.this.c.insertAtPos(complete,
                paragraphlst.getSelectedIndex());

Solution

  • In your code,

    complete.getContent().add(headline) 
    

    adds a paragraph inside a paragraph, which is invalid per the Open XML spec.