700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > JAVA - 使用Apache POI生成word(二) 设置纸张大小 调整纸张方向

JAVA - 使用Apache POI生成word(二) 设置纸张大小 调整纸张方向

时间:2023-02-06 06:38:57

相关推荐

JAVA - 使用Apache POI生成word(二) 设置纸张大小 调整纸张方向

JAVA - 使用Apache POI生成word(二) 设置纸张大小、调整纸张方向

前言

之前开发时,需要将纸张方向由纵向改为横向,查询资料得出只需要设置一下纸张的长度与宽度便可实现相同的效果。

1. pom引入依赖

<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.1</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.4</version></dependency>

2. 相关代码

import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.openxmlformats.schemas.wordprocessingml.x.main.CTPageSz;import org.openxmlformats.schemas.wordprocessingml.x.main.CTSectPr;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.math.BigInteger;

/*** 设置纸张大小** @param document doc对象* @param width 宽* @param height 长*/public static void setPageSize(XWPFDocument document, long width, long height) {CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();CTPageSz pgsz = sectPr.isSetPgSz() ? sectPr.getPgSz() : sectPr.addNewPgSz();pgsz.setW(BigInteger.valueOf(width));pgsz.setH(BigInteger.valueOf(height));}/*** 保存文件** @param document doc对象* @param savePath 保存路径* @param fileName 文件名称*/public static void saveDoc(XWPFDocument document, String savePath, String fileName) throws IOException {File file = new File(savePath);if (!file.exists()) {// 判断生成目录是否存在,不存在时创建目录。file.mkdirs();}// 保存fileName += ".docx";FileOutputStream out = new FileOutputStream(new File(savePath + File.separator + fileName));document.write(out);// 关闭资源out.flush();out.close();document.close();}public static void main(String[] args) throws IOException {XWPFDocument document = new XWPFDocument();// 将纸张大小设置为横向A4setPageSize(document, 16840, 11907);// 保存文件String savePath = "D:\\poi";String fileName = "PoiWord";saveDoc(document, savePath, fileName);}

结果如下:

width与height的取值规则

规则是纸张的长度(磅数)* 20

例横向A4纸的大小是 29.7(厘米)* 21(厘米),首先厘米转磅数在乘以20

宽:29.7 * 28.35 * 20 = 16839.9 ≈ 16840

长:21 * 28.35 * 20 = 11907

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。