We have already see the creation of Word file and adding Paragraph to it using Apache POI. Now we will see how to add Border to Paragraph in Word using POI.
Classes / Interfaces Used
XWPFDocument
org.apache.poi.xwpf.usermodel.XWPFDocument is used to create the MS Word Docs in the .docx formats.
XWPFParagraph
org.apache.poi.xwpf.usermodel.XWPFParagraph is used to create a paragraph in the word file.
XWPFRun
org.apache.poi.xwpf.usermodel.XWPFRun is used to add/change the text in a specified element/region.
The Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
package com.kscodes.test; 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 CreateBorderToParaWordDocPOI { public static void main(String args[]) { XWPFDocument document = null; FileOutputStream fileOutputStream = null; try { document = new XWPFDocument(); File fileToBeCreated = new File("C:\\kscodes_temp\\POI_Paragraph_Border_Test.docx"); fileOutputStream = new FileOutputStream(fileToBeCreated); // create Paragraph XWPFParagraph paragraph1 = document.createParagraph(); paragraph1.setBorderBottom(Borders.BASIC_THIN_LINES); paragraph1.setBorderLeft(Borders.BASIC_THIN_LINES); paragraph1.setBorderRight(Borders.BASIC_THIN_LINES); paragraph1.setBorderTop(Borders.BASIC_THIN_LINES); XWPFRun run = paragraph1.createRun(); run.setText("We created a word file using Apache POI. " + "And now we are writing into it as a paragraph. " + "Next, we will add some cool stuff to this Word document."); document.write(fileOutputStream); System.out.println("Paragraph created and Border added in Word File Succefully !!!"); } catch (Exception e) { System.out.println("We had an error while creating the Word Doc"); } finally { try { if (document != null) { document.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } catch (Exception ex) { } } } } |
Output
When we run the above code we get the message on the console and a word document with text and border around it is created at the location we had specified.
1 |
Paragraph created and Border added in Word File Succefully !!! |