Styles

Overview

This guide shows how to apply built-in heading styles to paragraphs, create a custom paragraph style with its own font and spacing, and read the styles back after saving a Word document in Java with Aspose.Words FOSS for Java. A style is a named set of character and paragraph formatting that paragraphs refer to, so that the look of a document is defined in one place. You can read the styles of a document, apply a built-in paragraph style such as a heading, and create your own paragraph style with a font and spacing. Document.getStyles returns the StyleCollection of a document; each entry is a Style whose getFont and getParagraphFormat hold its formatting. A paragraph’s style is set and read through its ParagraphFormat, by name with setStyleName or by StyleIdentifier with setStyleIdentifier. This page inspects the collection of a new document, applies headings, and creates and removes a custom style. All three examples were compiled and run against the published package on Java 8, 17 and 21 with the same output.


Prerequisites

RequirementDetail
Java8 or later
DependencyThe package from Installation
Importimport com.aspose.words.*;
CodeThe examples are statements. Put them in a method that declares throws Exception.

Inspect the Styles Collection

doc.getStyles() returns the collection and getCount its size; get(int) returns a style by index. A new Document held 4 styles: Normal, Default Paragraph Font, Table Normal and No List, of the types PARAGRAPH, CHARACTER, TABLE and LIST. get(String) looks a style up by name. For the English name of a built-in style that the document does not contain yet, such as Heading 1, it creates the style: the count went from 4 to 5. For a name that does not exist, such as Nope, it returned null, and the match is case sensitive, so heading 1 also returned null. The built-in Heading 1 style read back with the font Cambria 14 pt bold, 24 pt of space before, and Normal as its base and next style. After a save and reload the document still had 5 styles. To walk the collection use an index loop as in the example: in a test on Java 8, 17 and 21 a for-each loop over the collection returned the styles sorted by name, while get(int) returned them by index (the order in which they were added), an order that is not the sorted one.

import com.aspose.words.*;

Document doc = new Document();
StyleCollection styles = doc.getStyles();
System.out.println("Styles in a new document: " + styles.getCount());
for (int i = 0; i < styles.getCount(); i++) {
    Style style = styles.get(i);
    System.out.println(i + ": " + style.getName() + " (" + StyleType.getName(style.getType()) + ", built-in: " + style.getBuiltIn() + ")");
}

Style heading = styles.get("Heading 1");
System.out.println("Styles after looking up Heading 1: " + styles.getCount());
System.out.println("Name: " + heading.getName());
System.out.println("Is heading: " + heading.isHeading());
System.out.println("Font: " + heading.getFont().getName() + " " + heading.getFont().getSize() + " pt, bold: " + heading.getFont().getBold());
System.out.println("Space before: " + heading.getParagraphFormat().getSpaceBefore() + " pt");
System.out.println("Based on: " + heading.getBaseStyleName());
System.out.println("Next style: " + heading.getNextParagraphStyleName());

System.out.println("Style named Nope: " + styles.get("Nope"));
System.out.println("Style named heading 1: " + styles.get("heading 1"));

doc.save("styles.docx");
Document reloaded = new Document("styles.docx");
System.out.println("Styles after reload: " + reloaded.getStyles().getCount());

The program printed:

Styles in a new document: 4
0: Normal (PARAGRAPH, built-in: true)
1: Default Paragraph Font (CHARACTER, built-in: true)
2: Table Normal (TABLE, built-in: true)
3: No List (LIST, built-in: true)
Styles after looking up Heading 1: 5
Name: Heading 1
Is heading: true
Font: Cambria 14.0 pt, bold: true
Space before: 24.0 pt
Based on: Normal
Next style: Normal
Style named Nope: null
Style named heading 1: null
Styles after reload: 5

Apply Built-in Heading Styles

Set the style on builder.getParagraphFormat() before you write a paragraph. setStyleIdentifier(StyleIdentifier.HEADING_1) selects a built-in style by its identifier and setStyleName("Heading 2") selects one by name; StyleIdentifier.NORMAL and "Normal" return to the body style. The example saves the document, reloads it and reads each paragraph back with getStyleName, getStyleIdentifier and isHeading: Heading 1 has identifier 1 and Heading 2 has identifier 2, and both report true for isHeading, while Normal paragraphs have identifier 0 and report false. Naming a style that the document does not contain, here Missing, threw an IllegalStateException with the message Cannot find style 'Missing'.. In the saved file, word/document.xml refers to the styles with <w:pStyle w:val="Heading1" /> and <w:pStyle w:val="Heading2" />, and word/styles.xml contains a definition for each of them.

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.

Create a Custom Paragraph Style

doc.getStyles().add(StyleType.PARAGRAPH, "Callout") creates a user-defined paragraph style. Give it a base style with setBaseStyleName, a font through getFont and spacing and indents through getParagraphFormat; spacing and indents are in points. Apply it by name with setStyleName. Adding a second style with a name that exists threw an IllegalArgumentException with the message Cannot add a style because a style with the same name already exists.. After a save and reload the style read back as not built-in with Normal as its base style, Arial 11 pt bold, color 1F4E79, 6 pt before and 12 pt after and an 18 pt left indent. The first paragraph reported the style Callout and its first run read the font Arial 11 pt from the style. The saved word/styles.xml contains an entry with w:customStyle="1" for it, based on Normal, with the spacing in twentieths of a point (w:before="120" and w:after="240") and the left indent w:left="360". Style.remove removed the style from the document: get then returned null and the paragraph that used it reported the style Normal.

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

Tips and Best Practices

  • Select built-in styles with the StyleIdentifier constants where you can: Heading 1 is identified by StyleIdentifier.HEADING_1 (value 1), which does not depend on the spelling of the name, while StyleCollection.get(String) is case sensitive.
  • Set the style on the builder before you write the paragraph and set it back to Normal afterwards, as the second example does; every paragraph written in between has the style that was current when it was written.
  • Put formatting in the style rather than on each run. In the third example the run in the Callout paragraph reported Arial 11 pt, which it took from the style, and a style can be changed or removed in one place.

Common Issues

IssueCauseFix
The compiler reports cannot find symbol for Document.The com.aspose.words package is not imported.Add import com.aspose.words.*;.
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.
setStyleName throws an IllegalStateException with the message Cannot find style 'Missing'.The name is not a style of the document and not the English name of a built-in style.Create the style with StyleCollection.add first, or use the exact name of a built-in style such as Heading 2.
StyleCollection.add throws an IllegalArgumentException with the message Cannot add a style because a style with the same name already exists.The collection already holds a style with that name.Use the existing style, found with get, or choose another name.
StyleCollection.get returns null.No style has that name; the lookup is case sensitive, so heading 1 finds nothing while Heading 1 does.Spell the name as the style is named, or use getByStyleIdentifier for a built-in style.

FAQ

How do I make a paragraph a heading?

Call setStyleIdentifier(StyleIdentifier.HEADING_1) or setStyleName("Heading 1") on the ParagraphFormat of the builder or of a Paragraph, then write the text. After a reload ParagraphFormat.isHeading returned true for such paragraphs.

Can I change how a built-in style looks?

Yes. A test set the Heading 1 font to Arial 20 pt with a red color and 10 pt of space after, saved and reloaded the document, and the heading paragraph read back Arial, 20 pt and 10 pt of space after. Changing the size of a style in a loaded document to 14 pt changed the size that the runs of its paragraphs reported.

What happens to paragraphs when I remove their style?

In the third example, after Style.remove the paragraph that had used the style reported Normal. The upstream documentation says that all references to the removed style are removed from paragraphs, runs and tables.

Does a new document contain the heading styles?

No. A new Document holds 4 styles; Heading 1 appears in the collection once it is looked up with get or applied to a paragraph.


API Reference Summary

Class / MethodDescription
StyleCollectionA collection of Style objects that represent both the built-in and user-defined styles in a document.
StyleRepresents a single built-in or user-defined style.
Document.getStyles()Returns the collection of styles of the document.
StyleCollection.add(type, name)Creates a new user defined style and adds it the collection.
StyleCollection.get(name)Gets a style by name or alias. Case sensitive, returns null if the style with the given name is not found.
StyleCollection.getByStyleIdentifier(sti)Gets a built-in style by its locale independent identifier.
Style.getFont()Gets the character formatting of the style.
Style.getParagraphFormat()Gets the paragraph formatting of the style.
Style.remove()Removes the specified style from the document.
ParagraphFormat.getStyleName()Gets or sets the name of the paragraph style applied to this formatting.
ParagraphFormat.isHeading()True when the paragraph style is one of the built-in Heading styles.
StyleIdentifierLocale independent style identifier.
StyleTypeRepresents type of the style.

Related Guides

See Also