Apache poi, Docx file XWPFRun, XWPFParagraph

73 Views Asked by At

If anyone has a similar example or if someone can do it, please help me write it

I couldn't place the two images on the right and left sides of the word file.

The word file was created. but I could not change the position of the pictures in it and I had a problem placing the title between two pictures

1

There are 1 best solutions below

1
Axel Richter On

I hope you don't really want to fake official papers from The White House Office of Management and Budget.

As it looks like the header is in the header part of the Word document. And the simplest way to place the two logos as shown, is using a table. One would need a table in header part of the Word document. The table would need three columns and one row. The left cell in that row is left aligned and contains the left logo. The right cell in that row is right aligned and contains the right logo. The middle cell in that row is center aligned and contains the text.

How to create a table in header part of the Word document was answered already: How to add a table to header or footer?

But, of course Apache POI was further developed since this answer. Using current Apache POI version 5.2.3, code could look like so:

import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.util.Units;

import java.math.BigInteger;

public class CreateWordHeaderFooterTable {
    
 private static final int TWIPS_PER_INCH = 1440;

 public static void main(String[] args) throws Exception {
     
  try ( XWPFDocument doc = new XWPFDocument();
        FileOutputStream out = new FileOutputStream("./CreateWordHeaderFooterTable.docx");
      ) {

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

   paragraph = doc.createParagraph();
   run=paragraph.createRun();  
   run.setText("Lorem ipsum....");

   // the header content
   // create header start
   XWPFHeader header = doc.createHeader(HeaderFooterType.DEFAULT);
   
   // create table in header
   XWPFTable table = header.createTable(1, 3);
   // table spans full width
   table.setWidth("100%");
   // table has no borders
   table.removeBorders();
   // column widths
   double[] dWidthsPCT = new double[]{20d, 60d, 20d};
   java.util.stream.Stream<String> stream = 
    java.util.stream.DoubleStream.of(dWidthsPCT).boxed()
    .map(d -> String.valueOf(d)+"%");
   String[] widthsPCT = stream.toArray(String[]::new);  
   /*
    * Create CTTblGrid for this table with widths of the 3 columns. 
    * Necessary for Libreoffice/Openoffice to accept the column widths.
    */
   // only relations of column widths
   // f1rst col
   table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf((int)(dWidthsPCT[0]/100d * TWIPS_PER_INCH)));
   // second col
   table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf((int)(dWidthsPCT[1]/100d * TWIPS_PER_INCH)));
   // third col
   table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf((int)(dWidthsPCT[2]/100d * TWIPS_PER_INCH)));
   // get frist table row
   XWPFTableRow row = table.getRow(0); if (row == null) row = table.createRow();
   // set column widths
   XWPFTableCell cell;
   FileInputStream pictureIn;
   for (int i = 0; i < 3; i++) {
    cell = row.getCell(i); if (cell == null) cell = row.createCell();
    cell.setWidth(widthsPCT[i]);
   }
   // set cell contents
   // left cell
   cell = row.getCell(0);
   if (cell.getParagraphs().size() > 0) {
    paragraph = cell.getParagraphs().get(0);
   } else {
    paragraph = cell.addParagraph();   
   }
   paragraph.setAlignment(ParagraphAlignment.LEFT);
   run = paragraph.createRun();
   pictureIn = new FileInputStream("./leftLogo.png");
   run.addPicture(pictureIn, XWPFDocument.PICTURE_TYPE_PNG, "leftLogo.png", Units.toEMU(80), Units.toEMU(80));
   // right cell
   cell = row.getCell(2);
   if (cell.getParagraphs().size() > 0) {
    paragraph = cell.getParagraphs().get(0);
   } else {
    paragraph = cell.addParagraph();   
   }
   paragraph.setAlignment(ParagraphAlignment.RIGHT);
   run = paragraph.createRun();
   pictureIn = new FileInputStream("./rightLogo.png");
   run.addPicture(pictureIn, XWPFDocument.PICTURE_TYPE_PNG, "rightLogo.png", Units.toEMU(80), Units.toEMU(80));
   // middle cell
   cell = row.getCell(1);
   if (cell.getParagraphs().size() > 0) {
    paragraph = cell.getParagraphs().get(0);
   } else {
    paragraph = cell.addParagraph();   
   }
   paragraph.setAlignment(ParagraphAlignment.CENTER);
   run = paragraph.createRun();
   run.setText("LOREM IPSUM SEMIT DOLOR SIT AMET");
   run.addBreak();
   run.setText("consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata");

   // the footer content
   // create footer start
   XWPFFooter footer = doc.createFooter(HeaderFooterType.DEFAULT);
   paragraph = footer.getParagraphArray(0);
   if (paragraph == null) paragraph = footer.createParagraph();
   paragraph.setAlignment(ParagraphAlignment.CENTER);
   run = paragraph.createRun();  
   run.setText("The Footer:");
   
   // write out  
   doc.write(out);
  }
 }
}