简体   繁体   中英

Set word document page margins through java

I have created a file by using Java where I want to change page margins but I can't

Here is my code:

XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();    

paragraph.setAlignment(ParagraphAlignment.LEFT);
paragraph.setNumID(BigInteger.ONE);

run.setFontSize(18);

run.setText("Test");

    try{
        FileOutputStream output = new FileOutputStream("C://WordDocument.docx");
        document.write(output);

        output.close();

    } catch (Exception e){
        e.printStackTrace();
    }

What I want to do is something like document.setMarginLeft( Left_Margin ); and document.setMarginRight( Right_Margin );

Thanks in advance

我认为他/她的意思是ooxml-schemas库和rest依赖项

you need to get the body of the document and adding a Section, then adding a CTPageMar , this object proovide methods for setting margins for the section you just created.

this is actually working for me,

values are large i suppose 10000 is the total width of a page but i'm not sure about it, so find your own desidered values :)

    XWPFDocument doc = new XWPFDocument();
    CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
    CTPageMar pageMar = sectPr.addNewPgMar();
    pageMar.setLeft(BigInteger.valueOf(1500L));
    pageMar.setRight(BigInteger.valueOf(1500L));
    pageMar.setTop(BigInteger.valueOf(2000L));
    pageMar.setBottom(BigInteger.valueOf(1000L));

enjoy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM