Jeet
Jeet

Reputation: 395

How to implement the Hanging Indent in Word document with Apache poi?

enter image description here

I want to format the Word document with the help of Apache poi library in Java. As shown in the picture, after Item1 there is a tab space and then Name1 that has its own "Hanging Indent". I tried to create a paragraph and set its indentation but it did not work. I also tried to create seperate runners for the Item and Name but I could not implement the format perfect format as shown below in the picture.

I did the following but could not implement the result as shown in the picture above.

XWPFParagraph p1 = tableRowThree.getCell(2).addParagraph();
    p1.setIndentationHanging(-1100);
    p1.setAlignment(ParagraphAlignment.LEFT);
    XWPFRun run100=p1.createRun();
    run100.setText("Item1");
    run100.setBold(true);
    run100.setFontSize(11);
    CTR ctr0 = run100.getCTR();
    ctr0.addNewTab();
    XWPFRun run101=p1.createRun();
    run101.setText("Name1");

Upvotes: 0

Views: 671

Answers (1)

Axel Richter
Axel Richter

Reputation: 61915

A hanging indent consists of two settings.

At first the whole paragraph is left indent. And at second the first line in that paragraph get a hanging indent which places that first line before the left indent of the rest. If the hanging indent size is exactly the same as the left indent of the whole paragraph, then the first line starts at left page margin if the paragraph is in document body directly.

Complete Example to show this (tables aside to make this example easier to understand):

import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;

public class CreateWordHangingIndent {

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

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = null;
  XWPFRun run = null;
  
  paragraph = document.createParagraph();
  
  paragraph.setIndentFromLeft(1440); // indent from left 1440 Twips = 1 inch
  paragraph.setIndentationHanging(1440); // indentation hanging 1440 Twips = 1 inch
  
  run = paragraph.createRun();
  run.setText("Item1:");
  run.addTab();

  run = paragraph.createRun();
  run.setText("Name1");

  paragraph = document.createParagraph();
    
  paragraph.setIndentFromLeft(1440);
  paragraph.setIndentationHanging(1440);
  
  run = paragraph.createRun();
  run.setText("Item2:");
  run.addTab();

  run = paragraph.createRun();
  run.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."); 

  paragraph = document.createParagraph();

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

 }
}

The result is:

enter image description here

Upvotes: 2

Related Questions