Java (482)
The background of a Word document is blank by default. For documents like brochures, invitations, handouts, and marketing materials, blank backgrounds will be too tedious. A good-looking background can be a great attraction to readers. Therefore, you can add a color or insert an image as a background to make your documents more appealing. This article shows how to set background color or image for Word documents by programming using Spire.Doc for Java.
- Add a Background Color to a Word Document
- Add a Gradient Background to a Word Document
- Insert a Background Image to a Word Document
Install Spire.Doc for Java
First, 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>14.4.0</version>
</dependency>
</dependencies>
Add a Background Color to a Word Document
Adding a background color to a Word document is very easy. You only need to set the background type as color and then choose a color as your background. The detailed steps are as follows.
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Set the background type as color using Document.getBackground().setType() method.
- Set the background color using Document.getBackground().setColor() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.BackgroundType;
import java.awt.*;
import java.io.*;
public class addBackgroundColor {
public static void main(String[] args) throws IOException {
//Create an object of Document class
Document document= new Document();
//Load a Word document
document.loadFromFile("C:/Sample.docx");
//Set the background type as color
document.getBackground().setType(BackgroundType.Color);
//Set the background color as orange
document.getBackground().setColor(Color.orange);
//Save the document
document.saveToFile("AddBackgroundColor.docx", FileFormat.Docx);
}
}

Add a Gradient Background to a Word Document
Adding gradient background requires more steps. You need to set the background type as gradient, choose two colors, and then set shading variant and style. The detailed steps are as follows.
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Set the background type as gradient using Document.getBackground().setType() method.
- Choose two colors using >Background.getGradient().setColor1() and Background.getGradient().setColor2() method.
- Set shading variant using Background.getGradient().setShadingVariant() method.
- Set shading style using Background.getGradient().setShadingStyle() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.BackgroundType;
import com.spire.doc.documents.GradientShadingStyle;
import com.spire.doc.documents.GradientShadingVariant;
import java.awt.*;
import java.io.*;
public class addBackgroundColor {
public static void main(String[] args) throws IOException {
//load a word document
Document document= new Document("C:/Sample.docx");
//Set the background type as gradient
document.getBackground().setType(BackgroundType.Gradient);
//Choose two colors
Background background = document.getBackground();
background.getGradient().setColor1(Color.white);
background.getGradient().setColor2(Color.orange);
//Choose gradient variant
background.getGradient().setShadingVariant(GradientShadingVariant.Shading_Down);
//Choose gradient style
background.getGradient().setShadingStyle(GradientShadingStyle.Horizontal);
//Save the document
document.saveToFile("AddGradientBackground.docx", FileFormat.Docx_2013);
}
}

Insert Background Image to a Word Document
To insert a background picture to a Word document, you need to set the background type as picture, and then insert a picture as the background. The detailed steps are as follows.
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Change the background type to picture using Document.getBackground().setType() method.
- Insert a picture as the background using Document.getBackground().setPicture() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.BackgroundType;
import java.io.*;
public class addBackgroundColor {
public static void main(String[] args) throws IOException {
//Create an object of Document class
Document document= new Document();
//Load a Word document
document.loadFromFile("C:/Sample.docx");
//Set the background type as picture
document.getBackground().setType(BackgroundType.Picture);
//Set the background picture
document.getBackground().setPicture("C:/background.jpg");
//Save the document
document.saveToFile("AddBackgroundPicture.docx", FileFormat.Docx);
}
}

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.
Enabling security options of your Word documents is essential for keeping sensitive information safe. You can encrypt your document with a password so that it cannot be opened by unauthorized users; you can enable the Read-only mode to prevent users from changing the content; you can also partially restrict editing your document. This article demonstrates how to protect or unprotect Word documents in Java using Spire.Doc for Java.
- Protect a Word Document with a Password in Java
- Change Permission of a Word Document in Java
- Lock Specified Sections of a Word Document in Java
- Mark a Word Document as Final in Java
- Remove Password from an Encrypted Word Document 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>14.4.0</version>
</dependency>
</dependencies>
Protect a Word Document with a Password in Java
Encrypting a document with a password makes sure that only you and certain people can read or edit it. The following are the steps to password protect a Word document using Spire.Doc for Java.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Encrypt the document with a password using Document.encrypt() method.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class PasswordProtectWord {
public static void main(String[] args) {
//Create a Document object
Document document = new Document();
//Load a Word file
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Encrypt the document with a password
document.encrypt("open-psd");
//Save the document to another Word file
document.saveToFile("output/Encryption.docx", FileFormat.Docx);
}
}

Change Permission of a Word Document in Java
Documents encrypted with an open password cannot be opened by those who do not know the password. If you’d like to grant people permission to read your document but restrict the types of modifications that someone can make, you can set the document permission. The following are the steps to change permission of a Word document using Spire.Doc for Java.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Set the document permission and the permission password using Document.protect() method.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document;
import com.spire.doc.ProtectionType;
public class ChangePermission {
public static void main(String[] args) {
//Create a Document object
Document document = new Document();
//Load a Word document
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Set the document permission and set the permission password
document.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd");
//Save the document to another Word file
document.saveToFile("output/Permission.docx");
}
}

Lock Specified Sections of a Word Document in Java
You can lock parts of your Word document so that they cannot be changed and leave the unlocked parts available for editing. The following are the steps to protect specified sections of a Word document using Spire.Doc for Java.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Set the editing restriction as Allow_Only_Form_Fields.
- Unprotect a specific section by passing false to Section.protectForm() as a parameter. The rest sections will continue to be protected.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document;
import com.spire.doc.ProtectionType;
public class LockSpecificSections {
public static void main(String[] args) {
//Create a Document object
Document doc = new Document();
//Load a Word document
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Set editing restriction as "Allow_Only_Form_Fields"
doc.protect(ProtectionType.Allow_Only_Form_Fields, "permissionPsd");
//Unprotect section 2
doc.getSections().get(1).setProtectForm(false);
//Save the document to another Word file
doc.saveToFile("output/ProtectSection.docx");
}
}

Mark a Word Document as Final in Java
By marking a document as Final, you disable typing, editing, and format changes capabilities and a message will appear to any reader that the document has been finalized. The following are the steps to mark a Word document as final using Spire.Doc for Java.
- Create a Document object.
- Load a Word file using Document.loadFromFile() method.
- Get the CustomDocumentProperties object from the document.
- Add a custom property "_MarkAsFinal" to the document.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.CustomDocumentProperties;
import com.spire.doc.Document;
public class MarkAsFinal {
public static void main(String[] args) {
//Create a Document object
Document doc = new Document();
//Load a Word document
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Get custom document properties
CustomDocumentProperties customProperties = doc.getCustomDocumentProperties();
//Add "_MarkAsFinal" as a property to the document
customProperties.add("_MarkAsFinal", true);
//Save the document to another Word file
doc.saveToFile("output/MarkAsFinal.docx");
}
}

Remove Password from an Encrypted Word Document in Java
You can remove the password from an encrypted document if the encryption is no longer needed. The following are the detailed steps.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Remove the password using Document.removeEncryption() method.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class RemovePassword {
public static void main(String[] args) {
//Create a Document object
Document document = new Document();
//Load an encrypted Word document
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encryption.docx", FileFormat.Docx, "open-psd");
//Remove encryption
document.removeEncryption();
//Save the document to another Word file
document.saveToFile("output/RemoveEncryption.docx", FileFormat.Docx);
}
}
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.
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.
- Add Titles, Headings, and Paragraphs to a Word Document
- Add an Image to a Word Document
- Add a Table to a Word Document
- Add a List to a Word Document
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>14.4.0</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 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 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 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();
}
}

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.