Номер страницы в таблице - PullRequest
       59

Номер страницы в таблице

0 голосов
/ 25 октября 2019

Я создал метод, который добавляет таблицу в нижний колонтитул документа Word с одной строкой и тремя столбцами. Теперь я пытаюсь добавить номер страницы в средний столбец, и все, что я нашел, это добавить номер страницы прямо в нижний колонтитул. Я использую этот код, но я не смог этого сделать. Может кто-нибудь помочь, пожалуйста?

Это код, который работает для таблицы

static public void footer(XWPFDocument doc) {

    CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
    XWPFHeaderFooterPolicy footerPolicy= new XWPFHeaderFooterPolicy(doc, sectPr);

    XWPFFooter footer = footerPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);

    XWPFRun run;

    // create table in footer
    XWPFParagraph pgh1 = footer.createParagraph();
    XmlCursor cursor = pgh1.getCTP().newCursor();
    XWPFTable table = footer.insertNewTbl(cursor);
    XWPFTableRow row = table.getRow(0);
    if (row == null) row = table.createRow();
    int twipsPerInch = 1440;
    table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(7 * twipsPerInch));

    XWPFTableCell cell = row.getCell(0);
    if (cell == null) cell = row.createCell();
    CTTblWidth tblWidth = cell.getCTTc().addNewTcPr().addNewTcW();
    tblWidth.setW(BigInteger.valueOf(2 * twipsPerInch));
    tblWidth.setType(STTblWidth.DXA);
    pgh1 = cell.getParagraphs().get(0);
    run = pgh1.createRun();
    run.setText("blah blah blah");

    cell = row.getCell(1);
    if (cell == null) cell = row.createCell();
    tblWidth = cell.getCTTc().addNewTcPr().addNewTcW();
    tblWidth.setW(BigInteger.valueOf(3 * twipsPerInch));
    tblWidth.setType(STTblWidth.DXA);
    XWPFParagraph pageNumberParagraph = cell.getParagraphs().get(0); 
    pageNumberParagraph.setAlignment(ParagraphAlignment.CENTER);
    run = pageNumberParagraph.createRun();
    run.setText("1");

    cell = row.getCell(2);
    if (cell == null) cell = row.createCell();
    tblWidth = cell.getCTTc().addNewTcPr().addNewTcW();
    tblWidth.setW(BigInteger.valueOf(2 * twipsPerInch));
    tblWidth.setType(STTblWidth.DXA);
    pgh1 = cell.getParagraphs().get(0);
    pgh1.setAlignment(ParagraphAlignment.RIGHT);
    run = pgh1.createRun();
    run.setText("blah blah blah");
}

Затем я попытался добавить номер страницы, используя это, но я не могу понять это

CTPageNumber pgNum = sectPr.isSetPgNumType() ? sectPr.getPgNumType() : sectPr.addNewPgNumType();
pgNum.setStart(BigInteger.valueOf(1));

1 Ответ

1 голос
/ 25 октября 2019

См. Как добавить номера страниц в формате X из Y при создании текстового документа с помощью apache poi api? , чтобы узнать, как создать поля нумерации страниц в Word.

. Итак, создайте текстовый прогон и вставьте поля "PAGE \\* MERGEFORMAT" и / или "NUMPAGES \\* MERGEFORMAT" в эти текстовые прогоны. Это то, что также делает GUI Word.

...
run = paragraph.createRun();  
run.setText("Page ");
paragraph.getCTP().addNewFldSimple().setInstr("PAGE \\* MERGEFORMAT");
run = paragraph.createRun();  
run.setText(" of ");
paragraph.getCTP().addNewFldSimple().setInstr("NUMPAGES \\* MERGEFORMAT");
...

Те текстовые прогоны, которые, конечно, имеют эти поля, также могут находиться в ячейках таблицы.

Полный пример:

import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;

import org.apache.xmlbeans.XmlCursor;
import java.math.BigInteger;

public class CreateWordHeaderFooterTable {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  // the body content
  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run=paragraph.createRun();  
  run.setText("The Body:");

  paragraph = document.createParagraph();
  run=paragraph.createRun();  
  run.setText("Lorem ipsum.... page 1");

  paragraph = document.createParagraph();
  run=paragraph.createRun();
  run.addBreak(BreakType.PAGE); 
  run.setText("Lorem ipsum.... page 2");

  paragraph = document.createParagraph();
  run=paragraph.createRun();
  run.addBreak(BreakType.PAGE); 
  run.setText("Lorem ipsum.... page 3"); 

  // create header start
  XWPFHeader header = document.createHeader(HeaderFooterType.DEFAULT);

  paragraph = header.getParagraphArray(0);
  if (paragraph == null) paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);

  run = paragraph.createRun();  
  run.setText("The Header");

  // create footer start
  XWPFFooter footer = document.createFooter(HeaderFooterType.DEFAULT);

  // create table in footer
  paragraph = footer.getParagraphArray(0);
  if (paragraph == null) paragraph = footer.createParagraph();
  XmlCursor cursor = paragraph.getCTP().newCursor();
  XWPFTable table = footer.insertNewTbl(cursor);
  XWPFTableRow row = table.getRow(0); if (row == null) row = table.createRow();
  int twipsPerInch =  1440;
  table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(7 * twipsPerInch));
  for (int i = 0; i < 3; i++) {
   XWPFTableCell cell = row.getCell(i); if (cell == null) cell = row.createCell();
   CTTblWidth tblWidth = cell.getCTTc().addNewTcPr().addNewTcW();
   tblWidth.setW(BigInteger.valueOf(((i==1)?3:2) * twipsPerInch));
   tblWidth.setType(STTblWidth.DXA);
   paragraph = cell.getParagraphs().get(0);
   run = paragraph.createRun();
   if (i == 0) {
    paragraph.setAlignment(ParagraphAlignment.LEFT);
    run.setText("Left footer text");
   } else if (i == 1) {
    paragraph.setAlignment(ParagraphAlignment.CENTER);
    run.setText("Page ");
    paragraph.getCTP().addNewFldSimple().setInstr("PAGE \\* MERGEFORMAT");
    run = paragraph.createRun();  
    run.setText(" of ");
    paragraph.getCTP().addNewFldSimple().setInstr("NUMPAGES \\* MERGEFORMAT");
   } else if (i == 2) {
    paragraph.setAlignment(ParagraphAlignment.RIGHT);
    run.setText("Right footer text");
   }
  }

  FileOutputStream out = new FileOutputStream("CreateWordHeaderFooterTable.docx");
  document.write(out);
  out.close();
  document.close();

 }
}
...