Kiamur
Kiamur

Reputation: 125

Word autoformat with Apache-POI

I'd like to use the autoformat feature of word with Apache-POI in an XWPFDocument.

By autoformat I mean, if you type e.g. "---" and press return, a horizontal line is drawn across the page of the word document.

I'd like to use this in a header.

I tried

XWPFHeader header = doc.createHeader(HeaderFooterType.FIRST);
paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("---\r");

or

run.setText("---\r\n");

or

run.setText("---");
run.addCarriageReturn();

None of those work.

Is it even possible to use the autoformat function with POI?

Regards, Maik

I'm using POI 4.0.0, btw...

Upvotes: 0

Views: 342

Answers (1)

Axel Richter
Axel Richter

Reputation: 61945

The Autoformat is a feature of Word's GUI. But apache poi is creating what is stored in a *.docx file. After the Autoformat has replaced "---"Enter with a bottom border line of the paragraph, only this bottom border line of the paragraph is stored in the file.

So:

import java.io.*;

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

public class CreateWordHeader {

 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);
  paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);
  run = paragraph.createRun();
  run.setText("First Line in Header...");

  // bottom border line of the paragraph = what Autoformat creates after "---"[Enter]
  paragraph.setBorderBottom(Borders.SINGLE);

  paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);
  run = paragraph.createRun();
  run.setText("Next Line in Header...");

  FileOutputStream out = new FileOutputStream("CreateWordHeader.docx");
  doc.write(out);
  doc.close();
  out.close();


 }
}

Upvotes: 2

Related Questions