Java Program to Align the Text in a Word document
The text will be extracted first from a Word file using Apache in java. Apache POI let us allow access to Microsoft documents which includes Word, Excel, and PowerPoint. Java provides us various packages in-built into the environment, which facilitate the ease of reading, writing, and modifying the documents. The package org.apache.poi.xwpf.usermodel provides us the various features of formatting and appending the content in word documents. There are various classes available in this package like XWPFDocument to create a new Word document and XWPFParagraph to create and write new paragraphs into the corresponding created document. File class can be used to create a file at the specified path-name and FileOutputStream to create a file stream connection. The approach is simply first to create a paragraph, set alignment for it, and inserting text to it using inbuilt functions.
- Import the jar files while creating a package for java program and add the jar files9if necessarily as per IDE’s) and import File class.
- Call for XWPFDocument by creating an object of it.
- Passing FileInputStream as a parameter to deal with local directories
- Inside it pass the pathname or name the file with extensions.
- Create a blank file and FileOutputStream connection.
- Creating a paragraph using createParagraph() method.
- Set alignment using setAllignment() in built function.
- Insert text using setText() function.
- Write the content of a paragraph using XWPF class
- Close the connection.
Implementation: A blank Word document is supposed to be input in which processing is carried out to display the output in the same Word document after the processing.
XWPFDocument xwpfdocument =
File file =
XWPFParagraph para = xwpfdocument.createParagraph();
XWPFRun xwpfrun = para.createRun();
"Geeks for Geeks is a computer science portal which aims "
"to provide all in one platform for learning and "
"practicing.We can learn multiple "
"programming languages here. It also provided content for"
"UGC NET and JRF exams."
para = xwpfdocument.createParagraph();
xwpfrun = para.createRun();
"It also helps you to also prepare for various other "
"competitive exams.Also lets you prepare for interviews."
Output: The code creates a file in the local directory:
Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course
and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks