Open In App

How to Apply Borders to the Text in a Word Document using Java?

Java Library Apache POI will be used to apply borders to text in a Word Document in java. Apache POI is a project run by the Apache Software Foundation, and previously a sub-project of the Jakarta Project provides pure Java libraries for reading and writing files in Microsoft Office formats, such as Word, PowerPoint, and Excel. Use Apache guide to install the Apache POI libraries for Windows/Linux Systems.

Approach:



Illustration: Sample Input Image



Implementation:

Example:




// Java Program to apply borders to the text
// in a Word document
  
// Importing inout output classes
import java.io.*;
// importing Apache POI environment packages
import org.apache.poi.xwpf.usermodel.*;
  
// Class-BorderText
public class GFG {
  
    // Main driver method
    public static void main(String[] args) throws Exception
    {
  
        // Step 1: Creating a blank document
        XWPFDocument document = new XWPFDocument();
  
        // Step 2: Getting path of current working directory
        // to create the pdf file in the same directory of
        // the running java program
        String path = System.getProperty("user.dir");
        path += "/BorderText.docx";
  
        // Step 3: Creating a file object with the path specified
        FileOutputStream out
            = new FileOutputStream(new File(path));
  
        // Step 4: Create a paragraph
        XWPFParagraph paragraph
            = document.createParagraph();
  
        // Step 5: Setting borders
  
        // Set bottom border to paragraph
        paragraph.setBorderBottom(Borders.DASHED);
  
        // Set left border to paragraph
        paragraph.setBorderLeft(Borders.DASHED);
  
        // Set right border to paragraph
        paragraph.setBorderRight(Borders.DASHED);
  
        // Set top border to paragraph
        paragraph.setBorderTop(Borders.DASHED);
  
        XWPFRun line = paragraph.createRun();
        line.setText(
            "Whether programming excites you or you feel stifled"
            + ", wondering how to prepare for interview questions"
            + " or how to ace data structures and algorithms"
            + ", GeeksforGeeks is a one-stop solution.");
  
        // Step 6: Saving changes to document
        document.write(out);
  
        // Step 7: Closing the connections
        out.close();
        document.close();
  
        // Display message on console to illustrate
        // successful execution of the program
        System.out.println(
            "Word Document with Border Text created successfully!");
    }
}

Output:

Word Document with Border Text created successfully!

Output

Text is inserted in the same Word document and the border is successfully applied to the same text in a Word while comparing output image with sample input image taken as illustration to show changes to it after the implementation.


Article Tags :