java - 使用 Apache-POI 设置选项卡大小
问题描述
我想通过 Apache-POI 在 Word 文档中设置选项卡大小。
我有一个标题,它应该在它的标题行中包含两个字段,如下所示:
| filed1 -> field2 |
垂直线代表页面的边缘。我希望两个字段之间的选项卡很大,以便第一个字段与页面左对齐,右侧字段与页面右对齐。
使用Word本身很容易完成,但我只知道如何使用POI添加选项卡,而不是如何设置选项卡的宽度。
我尝试使用 Apaches tika 工具调查 Word 文件,但没有看到选项卡大小隐藏在文件中的位置。
任何帮助表示赞赏, Maik
解决方案
制表位是 Word 段落中的设置。尽管使用制表位是一件很常见的事情,也是文字处理中一个非常古老的过程,但如果不使用apache poi
.
例子:
注意:制表位位置的测量单位是缇(二十分之一英寸点)。
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTabStop;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabJc;
import java.math.BigInteger;
public class CreateWordHeaderWithTabStops {
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument();
// the body content
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The Body...");
// create header
XWPFHeader header = doc.createHeader(HeaderFooterType.FIRST);
// header's first paragraph
paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
// create tab stops
int twipsPerInch = 1440; //measurement unit for tab stop pos is twips (twentieth of an inch point)
CTTabStop tabStop = paragraph.getCTP().getPPr().addNewTabs().addNewTab();
tabStop.setVal(STTabJc.CENTER);
tabStop.setPos(BigInteger.valueOf(3 * twipsPerInch));
tabStop = paragraph.getCTP().getPPr().getTabs().addNewTab();
tabStop.setVal(STTabJc.RIGHT);
tabStop.setPos(BigInteger.valueOf(6 * twipsPerInch));
// first run in header's first paragraph, to be for first text box
run = paragraph.createRun();
run.setText("Left");
// add tab to run
run.addTab();
run = paragraph.createRun();
run.setText("Center");
// add tab to run
run.addTab();
run = paragraph.createRun();
run.setText("Right");
FileOutputStream out = new FileOutputStream("CreateWordHeaderWithTabStops.docx");
doc.write(out);
doc.close();
out.close();
}
}
推荐阅读
- spring-mvc - 使用 Spring RestTemplate,出现错误时如何记录响应?
- c - 从文件中读取数据的输入整数的排列生成所有可能的二叉树
- reactjs - 从对象数组生成表
- datagrid - UWP Community Toolkit DataGrid 控件:如何将单元格内容右对齐
- javascript - 减少函数给出“未捕获的类型错误:无法设置未定义的属性‘标题’”
- linux - 如何在 GCE 上的 CentOS 中调整 xfs 的大小?
- javascript - window.postMessage 从 iframe 到被调用者,iframe 和被调用者都在同一个域中
- android - 当其兄弟线性布局消失时,线性布局不会在其父级中垂直居中
- vue.js - 使用 Vue.js 和元素 UI,如何使必填字段可选取决于复选框值?
- docbook - 如何使用样式表自定义 Docbook?我在哪里可以找到好的资源?