How to Apply and Create Paragraph Styles in a Word Document in Java

How to Apply and Create Paragraph Styles in a Word Document in Java

Aspose.Words FOSS for Java applies a style to a paragraph through its ParagraphFormat and keeps the styles of a document in Document.getStyles. This guide applies the built-in heading styles and creates a custom paragraph style with its own font and spacing, saves the document and reads the styles back, with the library from Maven Central.

Step-by-Step Guide

Step 1: Install the Package

Add the package to your build. The library needs Java 8 or later.

<dependency>
  <groupId>org.aspose</groupId>
  <artifactId>aspose-words-foss</artifactId>
  <version>26.3.0</version>
</dependency>

Step 2: Import the Classes

All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;.


Step 3: Apply a Built-in Heading Style

On builder.getParagraphFormat() call setStyleIdentifier(StyleIdentifier.HEADING_1) or setStyleName("Heading 2"), write the paragraph, and call setStyleName("Normal") to return to the body style. After a save and reload getStyleName returned Heading 1, Normal, Heading 2 and Normal for the four paragraphs of the example, and the heading paragraphs reported identifiers 1 and 2.

import com.aspose.words.*;

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
builder.writeln("Quarterly report");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.NORMAL);
builder.writeln("Sales grew in every region.");
builder.getParagraphFormat().setStyleName("Heading 2");
builder.writeln("Regions");
builder.getParagraphFormat().setStyleName("Normal");
builder.writeln("Europe led the growth.");

try {
    builder.getParagraphFormat().setStyleName("Missing");
} catch (Exception e) {
    System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
doc.save("report.docx");

Document reloaded = new Document("report.docx");
NodeCollection paragraphs = reloaded.getChildNodes(NodeType.PARAGRAPH, true);
for (int i = 0; i < paragraphs.getCount(); i++) {
    Paragraph paragraph = (Paragraph) paragraphs.get(i);
    ParagraphFormat format = paragraph.getParagraphFormat();
    if (paragraph.getText().trim().length() > 0) {
        System.out.println(format.getStyleName() + " (identifier " + format.getStyleIdentifier() + ", heading: " + format.isHeading() + "): " + paragraph.getText().trim());
    }
}

The program printed:

IllegalStateException: Cannot find style 'Missing'.
Heading 1 (identifier 1, heading: true): Quarterly report
Normal (identifier 0, heading: false): Sales grew in every region.
Heading 2 (identifier 2, heading: true): Regions
Normal (identifier 0, heading: false): Europe led the growth.

Step 4: Create a Custom Paragraph Style

doc.getStyles().add(StyleType.PARAGRAPH, "Callout") returns the new Style. Set setBaseStyleName("Normal"), the font through getFont and the spacing through getParagraphFormat, then apply it with setStyleName("Callout").

import com.aspose.words.*;
import java.awt.Color;

Document doc = new Document();
Style callout = doc.getStyles().add(StyleType.PARAGRAPH, "Callout");
callout.setBaseStyleName("Normal");
callout.setNextParagraphStyleName("Normal");
callout.getFont().setName("Arial");
callout.getFont().setSize(11);
callout.getFont().setBold(true);
callout.getFont().setColor(new Color(0x1F, 0x4E, 0x79));
callout.getParagraphFormat().setSpaceBefore(6);
callout.getParagraphFormat().setSpaceAfter(12);
callout.getParagraphFormat().setLeftIndent(18);

DocumentBuilder builder = new DocumentBuilder(doc);
builder.getParagraphFormat().setStyleName("Callout");
builder.writeln("Back up the file before you start.");
builder.getParagraphFormat().setStyleName("Normal");
builder.writeln("Then open the document.");

try {
    doc.getStyles().add(StyleType.PARAGRAPH, "Callout");
} catch (Exception e) {
    System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
doc.save("callout.docx");

Document reloaded = new Document("callout.docx");
Style saved = reloaded.getStyles().get("Callout");
Color color = saved.getFont().getColor();
System.out.println("Style: " + saved.getName() + ", built-in: " + saved.getBuiltIn() + ", based on: " + saved.getBaseStyleName());
System.out.println("Font: " + saved.getFont().getName() + " " + saved.getFont().getSize() + " pt, bold: " + saved.getFont().getBold());
System.out.println("Color: " + String.format("%02X%02X%02X", color.getRed(), color.getGreen(), color.getBlue()));
System.out.println("Spacing: " + saved.getParagraphFormat().getSpaceBefore() + " pt before, " + saved.getParagraphFormat().getSpaceAfter() + " pt after");
System.out.println("Left indent: " + saved.getParagraphFormat().getLeftIndent() + " pt");

NodeCollection paragraphs = reloaded.getChildNodes(NodeType.PARAGRAPH, true);
Paragraph first = (Paragraph) paragraphs.get(0);
System.out.println("First paragraph style: " + first.getParagraphFormat().getStyleName());
System.out.println("First run font: " + first.getRuns().get(0).getFont().getName() + " " + first.getRuns().get(0).getFont().getSize() + " pt");

saved.remove();
System.out.println("Style Callout after remove: " + reloaded.getStyles().get("Callout"));
System.out.println("First paragraph style after remove: " + first.getParagraphFormat().getStyleName());

The program printed:

IllegalArgumentException: Cannot add a style because a style with the same name already exists.
Style: Callout, built-in: false, based on: Normal
Font: Arial 11.0 pt, bold: true
Color: 1F4E79
Spacing: 6.0 pt before, 12.0 pt after
Left indent: 18.0 pt
First paragraph style: Callout
First run font: Arial 11.0 pt
Style Callout after remove: null
First paragraph style after remove: Normal

Step 5: Read the Style Back

Reload the file and call getStyles().get("Callout"). The example read Arial 11 pt bold, color 1F4E79, 6 pt before, 12 pt after and an 18 pt left indent, and the first paragraph reported the style Callout.


Step 6: Remove the Style

Style.remove deletes the style from the document. In the example get then returned null and the paragraph that had used it reported Normal.

Common Issues and Fixes

setStyleName throws an exception. The IllegalStateException message was Cannot find style 'Missing'. The name is not a style of the document; create it with StyleCollection.add first or use the exact English name of a built-in style.

StyleCollection.add throws an exception. The IllegalArgumentException message was Cannot add a style because a style with the same name already exists. Use the existing style or choose another name.

StyleCollection.get returns null. No style has that name. The lookup is case sensitive: heading 1 returned null while Heading 1 returned the built-in style, which get creates if the document does not contain it yet.

The compiler reports an unreported exception. The Document constructors, Document.save and some other methods declare throws Exception. Declare it on the calling method or catch it.

Frequently Asked Questions

Does a new document contain the heading styles?

No. A new Document held 4 styles. Heading 1 is added when it is looked up with get or applied to a paragraph.

How do I tell whether a paragraph is a heading?

ParagraphFormat.isHeading returned true for paragraphs in the Heading 1 and Heading 2 styles after a reload.

In what unit are the spacing values?

Points. The example set 6, 12 and 18 and read the same values back; the saved file stores them in twentieths of a point (w:before="120", w:after="240", w:left="360").

See Also