2
votes

I'm a newbie of apache poi, and am using poi to write some data to docx file. Recently I encountered a problem of font, hope any body can give me some help.

I began the writing with an empty word file named empty.docx, as following.

InputStream input = getClass().getClassLoader().getResourceAsStream("empty.docx");
XWPFDocument document = new XWPFDocument(input);

In the empty.docx the default font is 'Arial', that means if you add any content they will inherit this font as long as you don't change the font manually.

But after I filled the content and write it to a new docx file,the default font was changed to 'Century'.

   OutputStream  output = new FileOutputStream("output.docx"); 
   document.write(output);

I want to change it back to 'Arial', but after a lot of search only found the methods to set font of XWPFRun.

run.getCTR().getRPr().getRFonts().setEastAsia(eastAsiaFontName);
run.getCTR().getRPr().getRFonts().setHAnsi(normalFontName);

I want to know if there is any method to change the global font of the whole document?

1
Do you not need to change the font on the Styles rather than paragraphs?Gagravarr
Yes, I need. After opening the empty.docx, I inserted some table in it, then filled some content to some of the table cells and set their fonts according to our requirements, and left others to empty. The question is the font of empty cell is 'Century', but not 'Arial'. If I do the same operations via MS Office Word, the font of empty cell should be 'Arial'.gonzalez lee
Don't you fix that in word by editing the normal or table style, and changing the font on that though?Gagravarr
Gagravarr, thanks for your reply. Yes, I can fix it by editing the style, but I wonder if I can do it programmatically.gonzalez lee
So just go ahead and change the style programtically?Gagravarr

1 Answers

3
votes

You can set the default font of the document like this (using your variable names):

XWPFStyles styles = document.createStyles();

CTFonts fonts = CTFonts.Factory.newInstance();
fonts.setEastAsia(eastAsiaFontName);
fonts.setHAnsi(normalFontName);

styles.setDefaultFonts(fonts);

I am currently stuck at how I set the default font size. That's why I found this question... The XWPFStyles class has a member "CTStyles ctStyles" with which it would be possible to define any property defined in the XML spec. But unfortunately it has only a public setter, but no getter.