How to set page orientation for a Word document?

I use Apache POI XWPF to create and process MS Word documents. But I did not find in the documentation how to change the page orientation.

Obviously, this method should do this:

 XWPFDocument doc = new XWPFDocument(); CTDocument1 document = doc.getDocument(); CTBody body = document.getBody(); if (!body.isSetSectPr()) { body.addNewSectPr(); } CTSectPr section = body.getSectPr(); if(!section.isSetPgSz()) { section.addNewPgSz(); } CTPageSz pageSize = section.getPgSz(); pageSize.setOrient(STPageOrientation.LANDSCAPE); 

But this method does not work correctly. I can set the page orientation to landscape, and when I read the page orientation in the code, I get a landscape. Fine. But if I open the saved document, I have a portrait format. This parameter does not work. What could be the problem?

As a workaround, I have to start working with a blank document created manually in landscape or portrait format. But I want to create documents programmatically from scratch in the right orientation.

For example, the HSSF and XSSF POIs have functionality for switching between landscape and portrait modes. This is the setLandscape () interface method org.apache.poi.ss.usermodel.PrintSetup .

But what about XWPF or HWPF ?

+5
java apache-poi orientation-changes landscape-portrait xwpf
source share
2 answers

You were on the right track. The landscape orientation setting describes the general orientation of the paper, but paper size will still be required. Your CTPageSz object does not already have this.

This means that in addition to your setOrient call, you need to set setW and setH. These calls are taken by BigIntegers, which are 1/20 Point representatives. Therefore, for landscape paper like LETTER, you simply:

 pageSize.setW(BigInteger.valueOf(15840)); pageSize.setH(BigInteger.valueOf(12240)); 

For Word to recognize it as landscape, the width must be greater than the height. You still want to save the setOrient call if you want it to work correctly when printing. A.

Here are some common paper sizes in points from https://www.gnu.org/software/gv/manual/html_node/Paper-Keywords-and-paper-size-in-points.html you should take them and multiply by twenty. to use in the above methods

 Letter 612x792 LetterSmall 612x792 Tabloid 792x1224 Ledger 1224x792 Legal 612x1008 Statement 396x612 Executive 540x720 A0 2384x3371 A1 1685x2384 A2 1190x1684 A3 842x1190 A4 595x842 A4Small 595x842 A5 420x595 B4 729x1032 B5 516x729 Folio 612x936 Quarto 610x780 10x14 720x1008 
+12
source share

The answer is correct.

I just needed to add additional dependencies in order to access the CTPageSz class.

 // SBT config "org.apache.poi" % "poi-ooxml" % "4.1.0", // Base library "org.apache.poi" % "ooxml-schemas" % "1.4", // required to access CTPageSz 
0
source share

All Articles