Apache POI Word - Borders



In this chapter, you will learn how to apply border to a paragraph using Java programming.

Create a Border

First of all, let us create a Paragraph using the referenced classes discussed in the earlier chapters. By following the previous chapter, create a Document first, and then we can create a Paragraph and apply the borders accordingly.

The following code snippet is used to set a border −

//Create Blank document
XWPFDocument document = new XWPFDocument();

//Create a blank spreadsheet
XWPFParagraph paragraph = document.createParagraph();

//Set bottom border to paragraph
paragraph.setBorderBottom(Borders.BASIC_BLACK_DASHES);

Example - Applying Borders to Paragraph in a document

The following code is used to apply Borders in a Document −

ApachePoiDocDemo.java

package com.tutorialspoint;

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.Borders;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class ApachePoiDocDemo {

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

      //Blank Document
      XWPFDocument document = new XWPFDocument(); 
        
      //Write the Document in file system
      FileOutputStream out = new FileOutputStream(new File("example.docx"));
        
      //create paragraph
      XWPFParagraph paragraph = document.createParagraph();
        
      //Set bottom border to paragraph
      paragraph.setBorderBottom(Borders.BASIC_BLACK_DASHES);
        
      //Set left border to paragraph
      paragraph.setBorderLeft(Borders.BASIC_BLACK_DASHES);
        
      //Set right border to paragraph
      paragraph.setBorderRight(Borders.BASIC_BLACK_DASHES);
        
      //Set top border to paragraph
      paragraph.setBorderTop(Borders.BASIC_BLACK_DASHES);
        
      XWPFRun run = paragraph.createRun();
         run.setText("At tutorialspoint.com, we strive hard to " +
         "provide quality tutorials for self-learning " +
         "purpose in the domains of Academics, Information " +
         "Technology, Management and Computer Programming " +
         "Languages.");
        
      document.write(out);
      out.close();
      document.close();  
      System.out.println("example.docx written successully");
   }
}

Output

If your system is configured with the POI library, then it will compile and execute to generate a Word document named example.docx in your current directory and display the following output −

example.docx written successfully

The example.docx file looks as follows −

Border Paragraph
Advertisements