首页 > 解决方案 > 使用 Apache-POI 设置选项卡大小

问题描述

我想通过 Apache-POI 在 Word 文档中设置选项卡大小。

我有一个标题,它应该在它的标题行中包含两个字段,如下所示:

|    filed1                  ->                   field2    |

垂直线代表页面的边缘。我希望两个字段之间的选项卡很大,以便第一个字段与页面左对齐,右侧字段与页面右对齐。

使用Word本身很容易完成,但我只知道如何使用POI添加选项卡,而不是如何设置选项卡的宽度。

我尝试使用 Apaches tika 工具调查 Word 文件,但没有看到选项卡大小隐藏在文件中的位置。

任何帮助表示赞赏, Maik

标签: javaapache-poi

解决方案


制表位是 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();


 }
}

推荐阅读