Page 1 of 1

Using Styles

PostPosted: Sun Jun 17, 2012 11:59 pm
by sandra
Hello,

Sorry for my english in advance because i'm not a native speaker. I'm new in this forum and docx4j.

I have created a kind of template document in which i want to store all my styles (such as heading 1/2/3/4, normal and so on)
I load the styles of this document in a new document
Code: Select all
//get styles from old document
WordprocessingMLPackage oldPkg = WordprocessingMLPackage.load(oldDoc);
Styles oldStyles = (Styles)oldPkg.getMainDocumentPart().getStyleDefinitionsPart().getJaxbElement();

//apply styles from old document to new document
WordprocessingMLPackage newPkg = WordprocessingMLPackage.createPackage();
StyleDefinitionsPart styleDefinitionsPart = new StyleDefinitionsPart();
styleDefinitionsPart.setPackage(newPkg);
styleDefinitionsPart.setJaxbElement(oldStyles);
newPkg.getMainDocumentPart().addTargetPart(styleDefinitionsPart);


and now I want to use these styles for my paragraphs. For this reason i would like to get a pStyle Object or something from my styleDefinitionsPart but i dont know how.

I also tried to work with a StyleTree
Code: Select all
mainDocumentPart.getStyleTree()

but i dont know how to get the style out of the style tree, because the single elements of the tree are nodes and can't converted to something like PStyle.

last but not least i tried to use the addStyledParagraphofText() function of mainDocumentPart directly but if i write something like this:

Code: Select all
mainDocumentPart.addStyledParagraphofText("heading 1", "My Text");


it doesnt work.

Now, after trying for about 4 hours i'm tired.

I hope anyone can tell me a solution.

In summary i want:

1) transfer my styles from one to another document (that works already)
2) use these transfered styles for my paragraphs

Looking forward for any reply.

Yours,
sandra

Re: Using Styles

PostPosted: Mon Jun 18, 2012 7:00 pm
by jason
You are on the right track with addStyledParagraphofText

If you look at document.xml for a docx created with Heading 1 style in Word, you'll see:

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
<w:pPr>
              <w:pStyle w:val="Heading1"/>
            </w:pPr>
 
Parsed in 0.000 seconds, using GeSHi 1.0.8.4


The corresponding style in styles.xml starts with:

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
        <w:style w:type="paragraph" w:styleId="Heading1">
          <w:name w:val="heading 1"/>
 
Parsed in 0.000 seconds, using GeSHi 1.0.8.4


so you can see you should be using the @w:styleId value, not the name.