好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

通过Java实现设置Word文档页边距的方法详解

页边距是指页面的边线到文字的距离。通常可在页边距内部的可打印区域中插入文字和图形,也可以将某些项目放置在页边距区域中(如页眉、页脚和页码等)。在我们用的Word文档中,都会设置页边距统一标准格式,页边距的标准为上下页边距为2.54CM,左右边距为2.8CM。边距也可以根据自己的需要进行更改。今天这篇文章将为您展示如何通过编程方式,设置Word 文档页边距。下面是我整理的具体步骤及方法,并附上Java代码供大家参考。

程序环境

方法1: 手动引入。将  Free Spire.Doc for Java  下载到本地,解压,找到lib文件夹下的Spire.Doc.jar文件。在IDEA中打开如下界面,将本地路径中的jar文件引入Java程序

方法2:  如果您想通过 Maven安装,则可以在 pom.xml 文件中添加以下代码导入 JAR 文件。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

< repositories >

         < repository >

             < id >com.e-iceblue</ id >

             < url >https://repo.e-iceblue.cn/repository/maven-public/</ url >

         </ repository >

     </ repositories >

< dependencies >

     < dependency >

         < groupId >e-iceblue</ groupId >

         < artifactId >spire.doc.free</ artifactId >

         < version >5.2.0</ version >

     </ dependency >

</ dependencies >

设置 Word 文档页边距

我们可以使用  Section.getPageSetup().getMargins()  方法来获取页面的页边距设置,再用 MarginsF 类下的方法设置上下左右页边距。详细操作步骤如下:

创建一个  Document  的对象。 使用  Document.loadFromFile()  方法载入 Word 文档。 使用  Document.getSections().get()  方法获取文档第一节。 使用  Section.getPageSetup().getMargins()  方法获取第一节的页边距。 分别使用  MarginsF.setTop() 、 MarginsF.setBottom() 、 MarginsF.setLeft() 、 MarginsF.setRight()  方法设置上下左右页边距。 使用  Document.saveToFile()  方法保存文档。

完整代码

Java

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

import com.spire.doc.Document;

import com.spire.doc.FileFormat;

import com.spire.doc.Section;

import com.spire.doc.documents.MarginsF;

 

public class setPageMargins {

     public static void main(String []args){

 

         //创建一个Document的对象

         Document document = new Document();

 

         //载入Word文档

         document.loadFromFile( "生死疲劳.docx" );

 

         //获取文档第一节

         Section section = document.getSections().get( 0 );

 

         //获取第一节的页边距

         MarginsF pageMargin = section.getPageSetup().getMargins();

 

         //设置第一节的上下左右页边距

         pageMargin.setTop( 17 .9f);

         pageMargin.setBottom( 17 .9f);

         pageMargin.setLeft( 17 .9f);

         pageMargin.setRight( 17 .9f);

 

         //保存文档

         document.saveToFile( "设置页边距.docx" , FileFormat.Docx_2013);

     }

}

效果图

到此这篇关于通过Java实现设置Word文档页边距的方法详解的文章就介绍到这了,更多相关Java设置Word页边距内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://www.cnblogs.com/Carina-baby/p/17144824.html

查看更多关于通过Java实现设置Word文档页边距的方法详解的详细内容...

  阅读:15次