The Wayback Machine - https://web.archive.org/web/20241001181449/https://www.geeksforgeeks.org/how-to-create-a-blank-word-document-using-java/
Open In App

How to Create a Blank Word Document using Java?

Last Updated : 08 Dec, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Apache POI and File stream is the root concept to create a Word document. Apache POI Is an API provided by Apache foundation which is a collection of different java libraries. This facility gives the library to read, write, and manipulate different Microsoft files such as Excel sheets, PowerPoint, and Word files. There are two types basically older version including ‘.doc’, ‘.ppt’ while newer versions of files as ‘.docx’, ‘.pptx’. There are two ways to deal with Apache POI as mentioned below:

Here zip file is taken for consideration and also if the operating system is Windows, zip files should be preferred. It is a simple java project so binary distribution API is used. In the process of creating the document, several paragraphs will be inserted as a sample to display output and will be providing styles to paragraphs such as font color, font name, and font size. 

Now in order to create a Word file without using Microsoft Word, there is a java interface called Spire and if there is a need to create a PDF document without using Adobe Acrobat then it can be done with the use of an interface known as ‘E-Ice blue’. Here ‘Spire.doc’ must have to be imported as per problem statement as all dealing is in word format.

Spire.Doc for Java is a professional Java Word API that enables Java applications to create, convert, manipulate, and print Word documents without using Microsoft Office. It will be imported as a reference for this program as a reference. 

Syntax: For importing libraries in java of Spire

import Spire.Doc.jar ;

Additionally, there is another Java API for PDF format as discussed above ‘E-Ice Blue’ that enables developers to read, write, convert, and print PDF documents in Java applications without using Adobe Acrobat. Similarly, a PowerPoint API allows developers to create, read, edit, convert, and print PowerPoint files within Java applications.

Now, just like any class Apache POI contains classes and methods to work on. Major components of Apache POI are discussed below to understand the internal working of a file, how it is been generated without Word with help of classes and methods. There are basically two versions of files been present in Word itself.

File Streams in Java itself is an abstract class so it has three classes InputStreamClass, OutputStreamClass, and ByteStreamClass to operational execution. When an I/O occurs through byte data is called Byte handling and when an I/O stream occurs with character stream then it is called file handling process with byte stream. Remember the base reference for the newer version of files is from Word version 3.5 onwards.

Approach:

  • File Handling provides how to read from and write to a file in Java. Java provides the basic input/output package for reading and writing streams. java.io package allows doing all the input and output tasks in java. Further, in detail is explained below under file streams in java.
  • Java contains an in-built package org.apache.poi.xwpf.usermodel which can be imported into the environment, providing a wide range of functionalities involved with documents. This package provides a class XWPFDocument which can be used to work with ‘.docx’ files. The other required package involves File for processing and working with files and FileOutputStream to establish a connection and create the corresponding file. It also stimulates the procedure of writing contents onto the specified file location. A blank document can be created and stored at the local storage using these packages. The connection needs to be closed after writing the contents.

Algorithm: To create a blank Word file

  1. Creating a blank document using file methods.
  2. Specifying the path or directory where the blank document is to be created.
  3. Writing to the document in the file stream.
  4. Writings contents to the document.
  5. Close the file connection.

Implementation: The following Java code illustrates this procedure: Here it is a simple Apache implementation program so no need to introduce Maven libraries to the program:

Java




// Java Program to Create 
// a Blank Word file
  
// Importing File libraries
import java.io.File;
import java.io.FileOutputStream;
  
// Importing Apache libraries
import org.apache.poi.xwpf.usermodel.XWPFDocument;
  
public class GFG {
  
    // Main driver method
    public static void main(String[] args) throws Exception
    {
  
        // Create a blank document
        XWPFDocument xwpfdocument = new XWPFDocument();
  
        // Create file by specifying the path
        File file = new File("C:/blankdocument.docx");
  
        // Writing document in file stream
        FileOutputStream ostream
            = new FileOutputStream(file);
  
        // Write contents to the document
        xwpfdocument.write(ostream);
  
        // Close the file connection
        ostream.close();
    }
}


Output: The code creates a blank document file in the local directory as specified by the programmer in the code.



Similar Reads

Java Program to Create a Blank PPT Document
Program to create a blank PPT document using Java. The external jar(Java archive) file is required for the creation of a new PPT document. Below is the implementation for the same. An object of XMLSlideShow class inside External Apache POI module is required for the creation of a new PPT. Algorithm: Created using the APACHE POI module.Creating a ne
1 min read
Java Program to Create a Word Document
A Word file is supposed to be created without Word with the help of Java application protocol interfaces. Concepts Involved: Apache POI and Maven Apache POI Is an API provided by Apache foundation which is a collection of different java libraries. This facility gives the library to read, write, and manipulate different Microsoft files such as Excel
6 min read
Java Program to Create blank Excel Sheet
ApachePOI stands for poor obfuscation Implementation which is a Java API for reading and writing Microsoft documents. It contains classes and interfaces namely Wordbook, Sheet, Row, and Cell. Apache POI can be used to access 'xlsx' extension files and as well as 'xlsx' extension files Concept: ApachePOI, jar files, and File methods are explained to
3 min read
How to Format the Text in a Word Document using 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. First do install Apache in order to import modules as per the guide for the ecosystem based on operating syste
3 min read
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
3 min read
Adding Images to a Word Document using Java
Java makes it possible to add images to Word documents using the addPicture() method of XWPFRun class provided by Apache POI package. Apache POI is a popular API developed and maintained by the Apache Software Foundation. It provides several classes and methods to perform different file operations on Microsoft office files using Java. In order to a
3 min read
Java Program to Write a Paragraph in a Word Document
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 cr
3 min read
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.usermod
3 min read
Java Program to Add Tables to a Word Document
OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. The library has more than 2500 optimized algorithms, which includes a comprehensive set of both classic and state-of-the-art computer vision. It has C++, Python, Java, and MATLAB interfaces and supports Windows, Linux, Android, and
3 min read
Java Program to Extract Paragraphs From a Word Document
The article demonstrates how to extract paragraphs from a word document using the getParagraphs() method of XWPFDocument class provided by the Apache POI package. Apache POI is a project developed and maintained by Apache Software Foundation that provides libraries to perform numerous operations on Microsoft office files using java. To extract para
2 min read
Java Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”
5 min read
Blank Final in Java
A final variable in Java can be assigned a value only once, we can assign a value either in declaration or later. final int i = 10; i = 30; // Error because i is final. A blank final variable in Java is a final variable that is not initialized during declaration. Below is a simple example of blank final. // A simple blank final example final int i;
2 min read
Static and non static blank final variables in Java
A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class: Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instan
5 min read
Setting the Position of the Image in PDF Document using Java
To set the Position of the Image in a PDF document using Java multiple external dependencies need to download first. Setting the Position of the Image in a PDF, use the iText library. These are the steps that should be followed to Set the Position of the Image in a PDF using java. 1. Creating a PdfWriter object: The PdfWriter class represents the D
3 min read
Creating an Empty PDF Document using Java
For creating a PDF document using Java, we need to know the packages/libraries which are necessary for writing the code. So, for creating a PDF doc, we will be using the iText 7 library. To know how to install this library in your workspace, you can follow this link. Creating An Empty PDF Doc To create an empty PDF Document, we first need to instan
3 min read
Removing Pages from a PDF Document using Java
Program to remove pages from an existing document a PDF document. The external jar file is required to import in the program. Below is the implementation for the same. Remove a page from an existing PDF document using the removePage() method of the PDDocument class. Approach: Load an existing PDF document using the static method load() of the PDDoc
2 min read
Drawing a Line in a PDF Document using Java
In this article, we will learn how to Draw a line in a PDF document using Java. For drawing a line in a PDF, we will use the iText library. These are the steps that should be followed to Draw a line in a PDF using java. 1. Creating a PdfWriter object The PdfWriter class represents the DocWriter for a PDF. The constructor of this class accepts a str
3 min read
Rotating an Image in a PDF Document Using Java
In this article, we will learn how to Rotating an Image in a PDF document using Java. For Rotating an Image in a PDF, we will use the iText library. These are the steps that should be followed to Rotating an Image in a PDF using java. 1. Creating a PdfWriter object The PdfWriter class represents the DocWriter for a PDF. The constructor of this clas
3 min read
Adding Pages to a PDF Document using Java
PDDocument class of 'org.apache.pdfbox.pdmodel' package which extends 'java.lang.Object'. is used. Declaration: public class PDDocument extends Object implements Pageable, Closeable Pre-requisite: Constructors PDDocument(): This constructor used to construct a new PDF document with zero pages.PDDocument(COSDocument doc): This constructor uses alrea
4 min read
How to Extract Content From a Text Document using Java?
There are several ways present in java to read the text file like BufferReader, FileReader, and Scanner. Each and every method provides a unique way of reading the text file. Methods: Using Files classUsing FileReader classUsing BufferReader classUsing Scanner class Let's see each and every method in detail with an example to get a better understan
10 min read
Java Program to Extract Content From a XML Document
An XML file contains data between the tags so it is complex to read the data when compared to other file formats like docx and txt. There are two types of parsers which parse an XML file: Object-Based (e.g. D.O.M)Event-Based (e.g. SAX, StAX) In this article, we will discuss how to parse XML using Java DOM parser and Java SAX parser. Java DOM Parser
6 min read
Java Program to Extract Content from a HTML document
HTML is the core of the web, all the pages you see on the internet are HTML, whether they are dynamically generated by JavaScript, JSP, PHP, ASP, or any other web technology. Your browser actually parses HTML and render it for you But if we need to parse an HTML document and find some elements, tags, attributes or check if a particular element exis
4 min read
Java Program to Extract Content from a TXT document
Java class< file using the Apache Tika library is used. For document type detection and content extraction from various file formats, it uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing different file formats. All these parser libraries are encapsulated
3 min read
What is Document Object in Java DOM?
Document Object Model is a commendation of the World Wide Web Consortium. It explains an interface that enables programs to access and modify the style, structure, and contents of XML documents. XML parsers that support DOM implement this interface. It can be clearly perceived from the image provided below as follows. When should one use a DOM pars
2 min read
How to Convert a Document to PDF in Java?
In software projects, there is quite often a requirement for conversion of a given file (HTML/TXT/etc.,) to a PDF file and similarly, any PDF file needs to get converted to HTML/TXT/etc., files. Even PDFs need to be stored as images of type PNG or GIF etc., Via a sample maven project, let us see the same. As it is the maven project, necessary depen
7 min read
Extracting each word from a String using Regex in Java
Given a string, extract words from it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Funny?? are not you? Output : Funny are not you Input : Geeks for geeks?? Output : Geeks for geeks We have discussed a solution for C++ in this post : Program to extract word
2 min read
Get the first letter of each word in a string using regex in Java
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extract the first letter of each word. It uses '/b'(on
1 min read
Java Program to Find Occurrence of a Word Using Regex
Java's regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex. Program to Find Occurrence of a Word Using RegexThe primary idea is to use Java's java.util.reg
2 min read
Java Program to Search a Particular Word in a String Using Regex
In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings. In this article, we will learn how to search for a particular word in a string using regex in Java. Regular Expressions:Pa
3 min read
Java Program to find the Last Index of a Particular Word in a String
To find out the last occurrence of a character or string from a given string across which the substring or character is been searched over and returning the index value of the character or substring is found. Real-life Example: Consider an example of a book. The book contains pages where pages contain words. Now if a user wants to figure out the oc
4 min read
Article Tags :
Practice Tags :