Create Word Document in Java

This article demonstrates how to create Word document, add paragraphs and set paragraph styles in Java using Spire.Doc for Java.

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;

import java.awt.*;

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

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

       //Add 3 paragraphs to the section
        Paragraph para1 = section.addParagraph();
        para1.appendText("Spire.Doc for Java");

        Paragraph para2 = section.addParagraph();
        para2.appendText("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.");

        Paragraph para3 = section.addParagraph();
        para3.appendText("A plenty of Word document processing tasks can be performed by Spire.Doc for Java, " +
                "such as create, read, edit, convert and print Word documents, insert image, add header and footer, " +
                "create table, add form field and mail merge field, add bookmark and watermark, add hyperlink, " +
                "set background color/image, add footnote and endnote, encrypt Word documents.");

        //Set title style for paragraph 1
        ParagraphStyle style1 = new ParagraphStyle(document);
        style1.setName("titleStyle");
        style1.getCharacterFormat().setBold(true);
        style1.getCharacterFormat().setTextColor(Color.BLUE);
        style1.getCharacterFormat().setFontName("Arial");
        style1.getCharacterFormat().setFontSize(12f);
        document.getStyles().add(style1);
        para1.applyStyle("titleStyle");

        //Set style for paragraph 2 and 3
        ParagraphStyle style2 = new ParagraphStyle(document);
        style2.setName("paraStyle");
        style2.getCharacterFormat().setFontName("Arial");
        style2.getCharacterFormat().setFontSize(11f);
        document.getStyles().add(style2);
        para2.applyStyle("paraStyle");
        para3.applyStyle("paraStyle");

        //Horizontally align paragraph 1 to center
        para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set first-line indent for paragraph 2 and 3
        para2.getFormat().setFirstLineIndent(25f);
        para3.getFormat().setFirstLineIndent(25f);

        //Set spaces after paragraph 1 and 2
        para1.getFormat().setAfterSpacing(15f);
        para2.getFormat().setAfterSpacing(10f);

        //Save the document
        document.saveToFile("Output.docx", FileFormat.Docx);
    }
}

Output:

Create Word Document in Java