添加阻止

时间:2018-02-28 15:26:42

标签: java docx4j

使用docx4j我将多个动态填充的subTemplates添加到我的主模板中 我不想在这些子模板中包含分页符(除非整页都太小而不适合)。 因此:如果subTemplate会在内部破坏,我想将整个subTemplate移动到下一页 我该怎么做?

到目前为止我的代码:

//... 
WordprocessingMLPackage mainTemplate = getWp();//ignore this method
List<WordprocessingMLPackage> projectTemplates = new ArrayList<>();

List<Project> projects = getProjects();//ignore this method
for (Project project : projects) {
  WordprocessingMLPackage template = getWpProject();//ignore this method
  //fill template with content from project
  //...
  projectList.add(template);
}

//Here's the part that will have to be changed I think:
//Since the projectTemplate only consists of tables I just added all its tables to the main template 
for (WordprocessingMLPackage temp : projectTemplates){
  List<Object> tables = doc.getAllElementFromObject(temp.getMainDocumentPart(), Tbl.class);
  for (Object table : tables) {
    mainTemplate.getMainDocumentPart().addObject(table);
  }
}

如果你能想出一种方法来改变.docx模板用Word来实现我的目标,请随时提出建议。
如果你有一般的代码改进建议,只需写一条评论。

1 个答案:

答案 0 :(得分:0)

我做了这个&#34;解决方法&#34;这对我很有用:
我将所有行计算在一起,并检查行内的文本是否中断(具有近似阈值) 然后我添加每个项目的行,一旦有太多行,我在当前项目之前插入一个中断并重新开始。

final int maxRowCountPerPage = 44;
final int maxLettersPerLineInDescr = 55;
int totalRowCount = 0;

WordprocessingMLPackage mainTemplate = getWp();

//Iterate over projects
for (Project project : getProjects()) {
  WordprocessingMLPackage template = this.getWpProject();
  String projectDescription = project.getDescr();

  //Fill template...

  //Count the lines
  int rowsInProjectDescr = (int) Math.floor((double) projectDescription.length() / maxLettersPerLineInDescr);
  int projectRowCount = 0;
  List<Object> tables = doc.getAllElementFromObject(template.getMainDocumentPart(), Tbl.class);
  for (Object table : tables) {
    List<Object> rows = doc.getAllElementFromObject(table, Tr.class);
    int tableRowCount = rows.size();
    projectRowCount += tableRowCount;
  }
  //System.out.println("projectRowCount before desc:" + projectRowCount);
  projectRowCount += rowsInProjectDescr;
  //System.out.println("projectRowCount after desc:" + projectRowCount);
  totalRowCount += projectRowCount;
  //System.out.println("totalRowCount: " + totalRowCount);

  //Break page if too many lines for page
  if (totalRowCount > maxRowCountPerPage) {
    addPageBreak(wp);
    totalRowCount = projectRowCount;
  }
  //Add project template to main template
  for (Object table : tables) {
    mainTemplate.getMainDocumentPart().addObject(table);
  }
}

如果你发现一种方法可以使代码更好,请在评论中告诉我!