How to Create Word Document using Java

In this tutorial, we will learn how to create Word document using Java. You can create the file in DOC or DOCX format which can contain text contents as well as images. The steps below can be used to create Word document using java with few simple steps.

Steps to Create Word document using Java

  1. Install Aspose.Words for Java from the Maven repository
  2. Create a blank Word document using the Document class object
  3. Initialize a new object of DocumentBuilder class"
  4. Insert a text string surrounded by a border
  5. Insert hyperlink
  6. Save the Word document

These simple steps configure required library and then initialize the Document class to create an empty document. Then it inserts text with hyperlink and proceeds to create Word Document in Java.

Code to Generate Word Document using Java

import com.aspose.words.License;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
public class CreateWordDocumentUsingJava {
public static void main(String[] args) throws Exception { //main function for CreateWordDocumentUsingJava
// Initialize a license to avoid trial version watermark in the output Word file
License license = new License();
license.setLicense("Aspose.Words.lic");
// Create a blank Word document file
Document doc = new Document();
// Initialize a new object of DocumentBuilder class
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a text string surrounded by a border
builder.getFont().getBorder().setColor(java.awt.Color.BLACK);
builder.getFont().getBorder().setLineWidth(2.5d);
builder.getFont().getBorder().setLineStyle(com.aspose.words.LineStyle.DASH_DOT_STROKER);
builder.write("Text surrounded by black border.");
// Remove all font formatting specified explicitly
builder.getFont().clearFormatting();
builder.insertBreak(com.aspose.words.BreakType.PARAGRAPH_BREAK);
builder.write("For further information, please visit the ");
// Insert a hyperlink and emphasize it with custom formatting
builder.getFont().setColor(java.awt.Color.BLUE);
builder.getFont().setUnderline(com.aspose.words.Underline.SINGLE);
builder.insertHyperlink("Aspose Knowledge Base", "https://kb.aspose.com/", false);
builder.getFont().clearFormatting();
builder.writeln(".");
// Save the document with compliance level
doc.save("WordDocumentCreatedUsingJava.docx");
}
}

This Java code snippet creates a Word document without needing to install any word processing application like MS Word. The feature to generate word document using Java with the above example mimics the behavior of MS Word application without being dependent on it.

In this example, we have explored how to create a Word document using Java. Moreover, if you want to learn how to generate a PDF file from HTML format, please refer to the article on how to generate PDF from HTML in Java.

 English