Apply style to specific text in a styled paragraph

2019-08-29 06:27发布

问题:

How to apply italic style to a specific text in a styled paragraph using Docx4j?

Let's say a paragraph, as below, has been added to a document and it already has a style.

word1 word2 word3 word4

What I need is to apply italic style to word3 and the general style of the paragraph is not modified, so words word1 word2 and word4 keep as is.

Thanks in advance.

回答1:

Sure, you'll need word3 to be in a run (w:r) of its own, so you can apply run property (w:rPr) of italics (w:i) to it.

So first, you'll need logic to split the run, if necessary.

Then simply apply the formatting. To see how to do that, create a docx (in Word say), with italics applied. The use the docx4j webapp or Word Helper AddIn to generate applicable code.



回答2:

I was able to achieve it by unmarshalling a text string as below:

p = (P) XmlUtils.unmarshalString(
    "<w:p xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\">"
    + "<w:pPr><w:pStyle w:val=\"style\"/></w:pPr>"
    + "<w:r><w:t xml:space=\"preserve\">word1 word2 </w:t></w:r>"
    + "<w:r><w:rPr><w:i/></w:rPr><w:t>word3</w:t></w:r>"
    + "<w:r><w:t xml:space=\"preserve\"> word4</w:t></w:r></w:p>");

And adding it to the document.



标签: java docx4j