Reputation: 23
XWPFParagraph bodyParagraph = docxModel.createParagraph(); bodypart.setalignment (ParagraphAlignment.RIGHT); XWPFRun paragraphConfig = bodyParagraph.createRun(); paragraphConfig.setFontSize(25); paragraphConfig.setText( "Hello world" );
Tell me how in one paragraph you can use different styles, for example, you need to write Hello in bold, and emphasize the world?
Upvotes: 0
Views: 571
Reputation: 61945
In a Word
document each text having different format needs to be in its own text-run. XWPFRun provides methods for direct formatting text.
So if the goal is one paragraph containing
Hello World
then the paragraph needs one text-run for Hello followed by one text-run for the space and one text-run for World.
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
public class CreateWordHelloWorld {
public static void main(String[] args) throws Exception {
XWPFDocument doc= new XWPFDocument();
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run;
//text run for "Hello" bold
run = paragraph.createRun();
run.setBold(true);
run.setFontSize(25);
run.setText("Hello");
//text run for space
run = paragraph.createRun();
run.setFontSize(25);
run.setText(" ");
//text run for "World" italic
run = paragraph.createRun();
run.setFontSize(25);
run.setItalic(true);
run.setText("World");
FileOutputStream out = new FileOutputStream("WordDocument.docx");
doc.write(out);
out.close();
doc.close();
}
}
Upvotes: 2