Creating Word documents programmatically in Java enables developers to automate report generation, invoice creation, and other document workflows with precision. With Spire.Doc for Java, you can dynamically build, format, and customize Word files directly from your applications-without relying on Microsoft Office.

This article guides you through the essential steps to generate a Word document from scratch, covering text formatting, image insertion, table creation, and list management. Whether you're producing business reports, contracts, or data-driven documents, this tutorial provides the foundation to streamline your document automation process in Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>13.11.2</version>
    </dependency>
</dependencies>

Add Titles, Headings, and Paragraphs to a Word Document in Java

When creating structured Word documents with Spire.Doc for .NET, its core functionality revolves around the Document and Section classes. Use the addParagraph() method to add new paragraphs and the appendText() method to insert text content. To ensure consistent formatting, you can apply built-in styles (such as Title or Heading 1-4), which achieve professional and standardized typesetting effects. You can also customize styles to precisely control fonts, colors, and sizes, thereby creating personalized document designs.

The steps to add titles, headings, and paragraphs to a Word document in Java are as follows:

  • Create a Document object.
  • Use Document.addSection() to add sections to the document.
  • Use Section.addParagraph() to add paragraphs to a section.
  • Apply built-in styles (Title, Heading1, Heading2, Heading3) to specific paragraphs using Paragraph.applyStyle().
  • Define a custom paragraph style using ParagraphStyle() and apply it to the specified paragraph.
  • Save the document as a DOCX file.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.Color;

public class CreateSimpleDocument {
    public static void main(String[] args) {

        // Create a Document object
        Document document = new Document();

        // Add a section
        Section section = document.addSection();

        // Set page margins
        section.getPageSetup().getMargins().setAll(60f);

        // Add a title paragraph
        Paragraph title_para = section.addParagraph();
        TextRange textRange = title_para.appendText("This Is Title");
        title_para.applyStyle(BuiltinStyle.Title);
        textRange.getCharacterFormat().setFontName("Times New Roman");

        // Add a couple of heading paragraphs
        Paragraph heading_one = section.addParagraph();
        textRange = heading_one.appendText("Heading 1");
        heading_one.applyStyle(BuiltinStyle.Heading_1);
        textRange.getCharacterFormat().setFontName("Times New Roman");

        Paragraph heading_two = section.addParagraph();
        textRange = heading_two.appendText("Heading 2");
        heading_two.applyStyle(BuiltinStyle.Heading_2);
        textRange.getCharacterFormat().setFontName("Times New Roman");

        Paragraph heading_three = section.addParagraph();
        textRange = heading_three.appendText("Heading 3");
        heading_three.applyStyle(BuiltinStyle.Heading_3);
        textRange.getCharacterFormat().setFontName("Times New Roman");

        Paragraph heading_four = section.addParagraph();
        textRange = heading_four.appendText("Heading 4");
        heading_four.applyStyle(BuiltinStyle.Heading_4);
        textRange.getCharacterFormat().setFontName("Times New Roman");

        // Add a normal paragraph
        Paragraph normal_para = section.addParagraph();
        normal_para.appendText("This is a sample paragraph.");

        // Create a paragraph style
        ParagraphStyle style = new ParagraphStyle(document);
        style.setName("paraStyle");
        style.getCharacterFormat().setFontName("Times New Roman");
        style.getCharacterFormat().setFontSize(13f);
        style.getCharacterFormat().setTextColor(Color.blue);
        document.getStyles().add(style);

        // Apply the custom style to the paragraph
        normal_para.applyStyle("paraStyle");

        // Save the document
        document.saveToFile("output/AddText.docx", FileFormat.Docx);

        // Dispose resources
        document.dispose();
    }
}

Add titles, headings and paragraphs to a Word document in java

Add an Image to a Word Document in Java

To insert an image into a Word document, you first need to create a dedicated paragraph element as the image container. By using the appendPicture() method, you can load an image from the file system and embed it directly into the document structure.

The steps to add an image to a Word document in Java are as follows:

  • Create a Document object.
  • Use Document.addSection() to add a section to the document.
  • Add a paragraph to the section using Section.addParagraph().
  • Insert the image into the paragraph using Paragraph.appendPicture().
  • Save the document as a DOCX file.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class AddImage {
    public static void main(String[] args) throws IOException {

        // Create a Document object
        Document document = new Document();

        // Add a section
        Section section = document.addSection();

        // Set page margins
        section.getPageSetup().getMargins().setAll(60f);

        // Add a paragraph
        Paragraph image_para = section.addParagraph();

        // Load an image file
        BufferedImage image =  ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\logo.png"));

        // Append it to the paragraph
        image_para.appendPicture(image);

        // Save the document
        document.saveToFile("output/AddImage.docx", FileFormat.Docx);

        // Dispose resources
        document.dispose();
    }
}

Add an image to a Word document in java

Add a Table to a Word Document in Java

The table creation process begins with the addTable() method, which is used to establish the basic table structure. Using the resetCells() method, you can specify the desired number of rows and columns. Once initialized, filling each cell with content requires first adding a paragraph element via the addParagraph() method, followed by inserting text using the appendText() method.

The steps to add a table to a Word document in Java are as follows:

  • Create a Document object.
  • Use Document.addSection() to add a section to the document.
  • Create a two-dimensional array to store table data (including headers and values).
  • Generate the table using Section.addTable().
  • Call the Table.resetCells() method to define the number of rows and columns based on the data.
  • Iterate through the data array and use the TableCell.addParagraph() and Paragraph.appendText() methods to add text to each cell.
  • Save the document as a DOCX file.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;

public class AddTable {
    public static void main(String[] args) {

        // Create a Document object
        Document document = new Document();

        // Add a section
        Section section = document.addSection();

        // Set page margins
        section.getPageSetup().getMargins().setAll(60f);

        // Define table data as a 2D array
        String[][] data = {
                {"Product", "Unit Price", "Quantity", "Sub Total"},
                {"A", "$29", "120", "$3,480"},
                {"B", "$35", "110", "$3,850"},
                {"C", "$68", "140", "$9,520"}
        };

        // Add a table
        Table table = section.addTable(true);

        // Set row number and column number
        table.resetCells(data.length, data[0].length);

        // Write data to cells
        for (int r = 0; r < data.length; r++) {
            TableRow row = table.getRows().get(r);
            row.setHeight(20);
            row.setHeightType(TableRowHeightType.Exactly);

            for (int c = 0; c < data[r].length; c++) {
                TableCell cell = row.getCells().get(c);
                cell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                TextRange textRange = cell.addParagraph().appendText(data[r][c]);
                textRange.getCharacterFormat().setFontName("Times New Roman");
                textRange.getCharacterFormat().setFontSize(14);
            }
        }

        // Automatically adjusts the column widths of a table to fit its contents
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        // Save the document to file
        document.saveToFile("output/AddTable.docx", FileFormat.Docx);

        // Dispose resources
        document.dispose();
    }
}

Add a table to a Word document in java

Add a List to a Word Document in Java

The ListStyle class provides the foundation for implementing bulleted lists and numbered lists in documents. By configuring this class, you can establish a unified visual format for all list items. Once the list style is defined, simply apply it to target paragraphs using the applyStyle() method.

The steps to add a list to a Word document in Java are as follows:

  • Create a Document object.
  • Use Document.addSection() to add a section to the document.
  • Define the list style using ListStyle().
  • Add paragraphs to the section using Section.addParagraph().
  • Apply the defined list style to paragraphs using Paragraph.getListFormat().applyStyle().
  • Save the document as a DOCX file.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;

public class AddList {
    public static void main(String[] args) {

        // Create a Document object
        Document document = new Document();

        // Add a section
        Section section = document.addSection();

        // Set page margins
        section.getPageSetup().getMargins().setAll(60f);

        // Create a bulleted list style
        ListStyle listStyle = new ListStyle(document, ListType.Bulleted);
        listStyle.setName("bulletedList");
        listStyle.getLevels().get(0).setBulletCharacter("\u00B7");
        listStyle.getLevels().get(0).getCharacterFormat().setFontName("Symbol");
        listStyle.getLevels().get(0).setTextPosition(20);
        document.getListStyles().add(listStyle);

        // Add a paragraph
        Paragraph paragraph = section.addParagraph();
        TextRange textRange = paragraph.appendText("Fruits:");
        paragraph.getFormat().setAfterSpacing(5f);
        textRange.getCharacterFormat().setFontName("Times New Roman");
        textRange.getCharacterFormat().setFontSize(14);

        // Add another four paragraphs as bulleted list items
        String[] fruits = {"Apple", "Banana", "Watermelon", "Mango"};
        for (String fruit : fruits) {
            paragraph = section.addParagraph();
            textRange = paragraph.appendText(fruit);
            paragraph.getListFormat().applyStyle(listStyle.getName());
            paragraph.getListFormat().setListLevelNumber(0);
            textRange.getCharacterFormat().setFontName("Times New Roman");
            textRange.getCharacterFormat().setFontSize(14);
        }

        // Save the document to file
        document.saveToFile("output/AddList.docx", FileFormat.Docx);

        // Dispose resources
        document.dispose();
    }
}

Add a list to a Word document in java

This tutorial provides a brief introduction to the basic operations of creating Word documents using Spire.Doc for Java, including core functionalities such as inserting titles, paragraphs, images, tables, and lists. For more comprehensive element additions and finer formatting settings, please refer to the official Spire.Doc online tutorials for complete guidance.

Get a Free License

To fully experience the capabilities of Spire.Doc for Java without any evaluation limitations, you can request a free 30-day trial license.

The appearance of a document conveys more than just document's message; it also reveals the information about the creator. A well-organized document that includes consistently formatted content and appropriate graphics, and that contains no spelling or grammatical mistakes, inspires greater trust in your ability to deliver a product or service.

Using Spire.Doc for Java, you're able to format entire paragraphs as well as individual words or phrases. This article focuses on introducing how to apply various types of formatting to characters in a Word document in Java using Spire.Doc for Java.

  • Font Name
  • Font Size
  • Font Color
  • Highlight Color
  • Bold
  • Italic
  • Underline
  • Strikethrough
  • Border
  • Shadow Effect
  • Emphasis Mark
  • Subscript and Superscript

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>13.11.2</version>
    </dependency>
</dependencies>

Apply Formatting to Characters in Word in Java

In order to apply formatting to a piece of text, you need to get the text in a TextRange and then format the characters within the TextRange using the methods under CharacterFormat class. The following are the steps to set character formatting in a Word document using Spire.Doc for Java.

  • Create a Document object.
  • Add a section to the document using Document.addSection() method.
  • Add a paragraph to the section using Section.addParagraph() method.
  • Append text to the paragraph using Paragraph.appendText() method and return a TextRange object.
  • Apply formatting such as font name, font size, border and highlight color to the characters within the text range using the methods under CharacterFormat class.
  • Save the document to a Word file using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.BorderStyle;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.SubSuperScript;
import com.spire.doc.documents.UnderlineStyle;
import com.spire.doc.fields.TextRange;
import com.spire.doc.fields.shape.Emphasis;

import java.awt.*;

public class ApplyFormattingToCharacters {

    public static void main(String[] args) {

        //Create a Document object
        Document document = new Document();

        //Add a section
        Section sec = document.addSection();

        //Add a paragraph
        Paragraph paragraph = sec.addParagraph();
        paragraph.appendText("Here is a paragraph with various character styles. This is ");

        //Append text to the paragraph and return a TextRange object
        TextRange tr = paragraph.appendText("text with strikeout");

        //Set the character format to strikeout via TextRange object
        tr.getCharacterFormat().isStrikeout(true);

        //Apply shadow effect to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text with shadow");
        tr.getCharacterFormat().isShadow (true);

        //Set font size
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text in a large font size");
        tr.getCharacterFormat().setFontSize(20);

        //Set font name
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text in the font of Arial Black");
        tr.getCharacterFormat().setFontName("Arial Black");

        //Set font color
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text in red");
        tr.getCharacterFormat().setTextColor(Color.red);

        //Apply bold & italic to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text in bold & italic");
        tr.getCharacterFormat().setBold(true);
        tr.getCharacterFormat().setItalic(true);

        //Apply underline to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("underlined text");
        tr.getCharacterFormat().setUnderlineStyle(UnderlineStyle.Single);

        //Apply background color to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text with highlight color");
        tr.getCharacterFormat().setHighlightColor(Color.green);

        //Apply border to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text with border");
        tr.getCharacterFormat().getBorder().setBorderType(BorderStyle.Single);
        tr.getCharacterFormat().getBorder().setColor(Color.black);

        //Apply emphasis mark to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text with emphasis mark");
        tr.getCharacterFormat().setEmphasisMark(Emphasis.Dot_Below);

        //Apply superscript to text
        paragraph.appendText(". This is a math formula: a");
        tr = paragraph.appendText("2");
        tr.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        paragraph.appendText(" + b");
        tr = paragraph.appendText("2");
        tr.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        paragraph.appendText(" = c");
        tr = paragraph.appendText("2");
        tr.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        paragraph.appendText(".");

        //Save to file
        document.saveToFile("output/SetCharacterFormat.docx", FileFormat.Docx);
    }
}

Java: Apply Formatting to Characters in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

A watermark is a very light image or text that sits in the background of a document. When you need to send a document to others, it’s common to add a watermark to the document to prevent unwarranted use or remind readers that the document is confidential or is a draft, sample, etc. In this article, you will learn how to programmatically add a text watermark or an image watermark to a Word document using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>13.11.2</version>
    </dependency>
</dependencies>

Add a Text Watermark to Word

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method.
  • Create a TextWatermark instance.
  • Set the text, font size, color and layout of the text watermark using the methods offered by TextWatermark class.
  • Add the text watermark to sample document using Section.getDocument().setWatermark() method.
  • Save the document to file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.WatermarkLayout;
import java.awt.*;

public class WordTextWatermark {
    public static void main(String[] args) {
        //Create a Document instance
        Document document = new Document();

        //Load a sample Word document
        document.loadFromFile("Sample.docx");

        //Get the first section
        Section section = document.getSections().get(0);

        //Create a TextWatermark instance
        TextWatermark txtWatermark = new TextWatermark();

        //Set the format of the text watermark
        txtWatermark.setText("Confidential");
        txtWatermark.setFontSize(40);
        txtWatermark.setColor(Color.red);
        txtWatermark.setLayout(WatermarkLayout.Diagonal);

        //Add the text watermark to document
        section.getDocument().setWatermark(txtWatermark);

        //Save the document to file
        document.saveToFile("out/result.docx", FileFormat.Docx);
    }

}

Java: Add Text Watermarks or Image Watermarks to Word

Add an Image Watermark to Word

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.loadFromFile() method.
  • Create a PictureWatermark instance.
  • Load an image as the image watermark using PictureWatermark.setPicture() method, and then set scaling as well as washout property of the image watermark using PictureWatermark.setScaling() method and PictureWatermark.isWashout() method.
  • Add the image watermark to sample document using Document.setWatermark() method.
  • Save the document to file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;


public class WordImageWatermark {
    public static void main(String[] args)  throws Exception{
        //Create a Document instance
        Document document = new Document();

        //Load a sample Word document
        document.loadFromFile("Sample.docx");

        //Create a PictureWatermark instance
        PictureWatermark picture = new PictureWatermark();

        //Set the format of the picture watermark
        picture.setPicture("logo.png");
        picture.setScaling(100);
        picture.isWashout(false);

        //Add the image watermark to document
        document.setWatermark(picture);

        //Save the result file
        document.saveToFile("out/result2.docx",FileFormat.Docx );
    }
}

Java: Add Text Watermarks or Image Watermarks to Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

page 69