How to: Create and add a paragraph style to a word processing document
TOC
Collapse the table of content
Expand the table of content

How to: Create and add a paragraph style to a word processing document (Open XML SDK)

Office 2013 and later

Last modified: March 25, 2013

Applies to: Office 2013 | Open XML

In this article
CreateAndAddParagraphStyle Method
About Style IDs, Style Names, and Aliases
Calling the Sample Method
Style Types
Paragraph Style Type
How the Code Works
Creating the Style
Applying the Paragraph Style
Sample Code

This topic shows how to use the classes in the Open XML SDK 2.5 for Office to programmatically create and add a paragraph style to a word processing document. It contains an example CreateAndAddParagraphStyle method to illustrate this task, plus a supplemental example method to add the styles part when necessary.

To use the sample code in this topic, you must install the Open XML SDK 2.5. You must also explicitly reference the following assemblies in your project:

  • WindowsBase

  • DocumentFormat.OpenXml (installed by the Open XML SDK)

You must also use the following using directives or Imports statements to compile the code in this topic.

Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing

The CreateAndAddParagraphStyle sample method can be used to add a style to a word processing document. You must first obtain a reference to the style definitions part in the document to which you want to add the style. For more information and an example of how to do this, see the Calling the Sample Method section.

The method accepts four parameters that indicate: a reference to the style definitions part, the style ID of the style (an internal identifier), the name of the style (for external use in the user interface), and optionally, any style aliases (alternate names for use in the user interface).

Public Sub CreateAndAddParagraphStyle(ByVal styleDefinitionsPart As StyleDefinitionsPart, 
ByVal styleid As String, ByVal stylename As String, Optional ByVal aliases As String = "")

The complete code listing for the method can be found in the Sample Code section.

The style ID is used by the document to refer to the style, and can be thought of as its primary identifier. Typically you use the style ID to identify a style in code. A style can also have a separate display name in the user interface. Often, the style name therefore appears in proper case and with spacing (for example, Heading 1), while the style ID is more succinct (for example, heading1) and intended for internal use. Aliases specify alternate style names that can be used by the user interface of an application.

For example, consider the following XML code example taken from a style definition.

<w:style w:type="paragraph" w:styleId="OverdueAmountPara" . . .
  <w:aliases w:val="Late Due, Late Amount" />
  <w:name w:val="Overdue Amount Para" />
. . .
</w:style>

The styleId attribute of the style element holds the main internal identifier of the style, the style ID (OverdueAmountPara). The aliases element specifies two alternate style names, Late Due, and Late Amount, which are comma separated. Each name must be separated by one or more commas. Finally, the name element specifies the primary style name, which is the one typically shown in the user interface of an application.

Use the CreateAndAddParagraphStyle example method to create and add a named style to a word processing document using the Open XML SDK. The following code example shows how to open and obtain a reference to a word processing document, retrieve a reference to the style definitions part of the document, and then call the CreateAndAddParagraphStyle method.

To call the method, pass a reference to the style definitions part as the first parameter, the style ID of the style as the second parameter, the name of the style as the third parameter, and optionally, any style aliases as the fourth parameter. For example, the following code creates the "Overdue Amount Para" paragraph style in a sample file that is named CreateAndAddParagraphStyle.docx. It also adds a paragraph of text, and applies the style to the paragraph.

Dim strDoc As String = "C:\Users\Public\Documents\CreateAndAddParagraphStyle.docx"

Using doc As WordprocessingDocument =
    WordprocessingDocument.Open(strDoc, True)

    ' Get the Styles part for this document.
    Dim part As StyleDefinitionsPart =
        doc.MainDocumentPart.StyleDefinitionsPart

    ' If the Styles part does not exist, add it.
    If part Is Nothing Then
        part = AddStylesPartToPackage(doc)
    End If

    ' Set up a variable to hold the style ID.
    Dim parastyleid As String = "OverdueAmountPara"

    ' Create and add a paragraph style to the specified styles part 
    ' with the specified style ID, style name and aliases.
    CreateAndAddParagraphStyle(part,
        parastyleid,
        "Overdue Amount Para",
        "Late Due, Late Amount")

    ' Add a paragraph with a run and some text.
    Dim p As New Paragraph(
        New Run(
            New Text("This is some text in a run in a paragraph.")))

    ' Add the paragraph as a child element of the w:body element.
    doc.MainDocumentPart.Document.Body.AppendChild(p)

    ' If the paragraph has no ParagraphProperties object, create one.
    If p.Elements(Of ParagraphProperties)().Count() = 0 Then
        p.PrependChild(Of ParagraphProperties)(New ParagraphProperties())
    End If

    ' Get a reference to the ParagraphProperties object.
    Dim pPr As ParagraphProperties = p.ParagraphProperties

    ' If a ParagraphStyleId object doesn't exist, create one.
    If pPr.ParagraphStyleId Is Nothing Then
        pPr.ParagraphStyleId = New ParagraphStyleId()
    End If

    ' Set the style of the paragraph.
    pPr.ParagraphStyleId.Val = parastyleid
End Using

WordprocessingML supports six style types, four of which you can specify using the type attribute on the style element. The following information, from section 17.7.4.17 in the ISO/IEC 29500 specification, introduces style types.

Style types refers to the property on a style which defines the type of style created with this style definition. WordprocessingML supports six types of style definitions by the values for the style definition's type attribute:

  • Paragraph styles

  • Character styles

  • Linked styles (paragraph + character) [Note: Accomplished via the link element (§17.7.4.6). end note]

  • Table styles

  • Numbering styles

  • Default paragraph + character properties

[Example: Consider a style called Heading 1 in a document as follows:

<w:style w:type="paragraph" w:styleId="Heading1">
  <w:name w:val="heading 1"/>
  <w:basedOn w:val="Normal"/>
  <w:next w:val="Normal"/>
  <w:link w:val="Heading1Char"/>
  <w:uiPriority w:val="1"/>
  <w:qformat/>
  <w:rsid w:val="00F303CE"/>
  …
</w:style>

The type attribute has a value of paragraph, which indicates that the following style definition is a paragraph style. end example]

© ISO/IEC29500: 2008.

You can set the paragraph, character, table and numbering styles types by specifying the corresponding value in the type attribute of the style element.

You specify paragraph as the style type by setting the value of the type attribute on the style element to "paragraph".

The following information from section 17.7.8 of the ISO/IEC 29500 specification discusses paragraph styles. Note that section numbers preceded by § indicate sections in the ISO specification.

17.7.8 Paragraph Styles

Paragraph styles are styles which apply to the contents of an entire paragraph as well as the paragraph mark. This definition implies that the style can define both character properties (properties which apply to text within the document) as well as paragraph properties (properties which apply to the positioning and appearance of the paragraph). Paragraph styles cannot be referenced by runs within a document; they shall be referenced by the pStyle element (§17.3.1.27) within a paragraph’s paragraph properties element.

A paragraph style has three defining style type-specific characteristics:

  • The type attribute on the style has a value of paragraph, which indicates that the following style definition is a paragraph style.

  • The next element defines an editing behavior which supplies the paragraph style to be automatically applied to the next paragraph when ENTER is pressed at the end of a paragraph of this style.

  • The style specifies both paragraph-level and character-level properties using the pPr and rPr elements, respectively. In this case, the run properties are the set of properties applied to each run in the paragraph.

The paragraph style is then applied to paragraphs by referencing the styleId attribute value for this style in the paragraph properties’ pStyle element.

© ISO/IEC29500: 2008.

The CreateAndAddParagraphStyle method begins by retrieving a reference to the styles element in the styles part. The styles element is the root element of the part and contains all of the individual style elements. If the reference is null, the styles element is created and saved to the part.

' Access the root element of the styles part.
    Dim styles As Styles = styleDefinitionsPart.Styles
    If styles Is Nothing Then
        styleDefinitionsPart.Styles = New Styles()
        styleDefinitionsPart.Styles.Save()
    End If

To create the style, the code instantiates the Style class and sets certain properties, such as the Type of style (paragraph), the StyleId, whether the style is a CustomStyle, and whether the style is the Default style for its type.

' Create a new paragraph style element and specify some of the attributes.
Dim style As New Style() With { .Type = StyleValues.Paragraph, _
 .StyleId = styleid, _
 .CustomStyle = True, _
 .[Default] = False}

The code results in the following XML.

<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:style w:type="paragraph" w:styleId="OverdueAmountPara" w:default="false" w:customStyle="true">
  </w:style>
</w:styles>

The code next creates the child elements of the style, which define the properties of the style. To create an element, you instantiate its corresponding class, and then call the Append([]) method add the child element to the style. For more information about these properties, see section 17.7 of the ISO/IEC 29500 specification.

' Create and add the child elements (properties of the style)
Dim aliases1 As New Aliases() With {.Val = aliases}
Dim autoredefine1 As New AutoRedefine() With {.Val = OnOffOnlyValues.Off}
Dim basedon1 As New BasedOn() With {.Val = "Normal"}
Dim linkedStyle1 As New LinkedStyle() With {.Val = "OverdueAmountChar"}
Dim locked1 As New Locked() With {.Val = OnOffOnlyValues.Off}
Dim primarystyle1 As New PrimaryStyle() With {.Val = OnOffOnlyValues.[On]}
Dim stylehidden1 As New StyleHidden() With {.Val = OnOffOnlyValues.Off}
Dim semihidden1 As New SemiHidden() With {.Val = OnOffOnlyValues.Off}
Dim styleName1 As New StyleName() With {.Val = stylename}
Dim nextParagraphStyle1 As New NextParagraphStyle() With { _
 .Val = "Normal"}
Dim uipriority1 As New UIPriority() With {.Val = 1}
Dim unhidewhenused1 As New UnhideWhenUsed() With { _
 .Val = OnOffOnlyValues.[On]}
If aliases <> "" Then
    style.Append(aliases1)
End If
style.Append(autoredefine1)
style.Append(basedon1)
style.Append(linkedStyle1)
style.Append(locked1)
style.Append(primarystyle1)
style.Append(stylehidden1)
style.Append(semihidden1)
style.Append(styleName1)
style.Append(nextParagraphStyle1)
style.Append(uipriority1)
style.Append(unhidewhenused1)

Next, the code instantiates a StyleRunProperties object to create a rPr (Run Properties) element. You specify the character properties that apply to the style, such as font and color, in this element. The properties are then appended as children of the rPr element.

When the run properties are created, the code appends the rPr element to the style, and the style element to the styles root element in the styles part.

' Create the StyleRunProperties object and specify some of the run properties.
Dim styleRunProperties1 As New StyleRunProperties()
Dim bold1 As New Bold()
Dim color1 As New Color() With { _
 .ThemeColor = ThemeColorValues.Accent2}
Dim font1 As New RunFonts() With { _
 .Ascii = "Lucida Console"}
Dim italic1 As New Italic()
' Specify a 12 point size.
Dim fontSize1 As New FontSize() With { _
 .Val = "24"}
styleRunProperties1.Append(bold1)
styleRunProperties1.Append(color1)
styleRunProperties1.Append(font1)
styleRunProperties1.Append(fontSize1)
styleRunProperties1.Append(italic1)

' Add the run properties to the style.
style.Append(styleRunProperties1)

' Add the style to the styles part.
styles.Append(style)

When you have the style created, you can apply it to a paragraph by referencing the styleId attribute value for this style in the paragraph properties’ pStyle element. The following code example shows how to apply a style to a paragraph referenced by the variable p. The style ID of the style to apply is stored in the parastyleid variable, and the ParagraphStyleId property represents the paragraph properties’ pStyle element.

' If the paragraph has no ParagraphProperties object, create one.
If p.Elements(Of ParagraphProperties)().Count() = 0 Then
    p.PrependChild(Of ParagraphProperties)(New ParagraphProperties())
End If

' Get a reference to the ParagraphProperties object.
Dim pPr As ParagraphProperties = p.ParagraphProperties

' If a ParagraphStyleId object does not exist, create one.
If pPr.ParagraphStyleId Is Nothing Then
    pPr.ParagraphStyleId = New ParagraphStyleId()
End If

' Set the style of the paragraph.
pPr.ParagraphStyleId.Val = parastyleid

The following is the complete CreateAndAddParagraphStyle code sample in both C# and Visual Basic.

' Create a new paragraph style with the specified style ID, primary style name, and aliases and 
' add it to the specified style definitions part.
Public Sub CreateAndAddParagraphStyle(ByVal styleDefinitionsPart As StyleDefinitionsPart,
    ByVal styleid As String, ByVal stylename As String, Optional ByVal aliases As String = "")

    ' Access the root element of the styles part.
    Dim styles As Styles = styleDefinitionsPart.Styles
    If styles Is Nothing Then
        styleDefinitionsPart.Styles = New Styles()
        styleDefinitionsPart.Styles.Save()
    End If

    ' Create a new paragraph style element and specify some of the attributes.
    Dim style As New Style() With { _
     .Type = StyleValues.Paragraph, _
     .StyleId = styleid, _
     .CustomStyle = True, _
     .[Default] = False}

    ' Create and add the child elements (properties of the style)
    Dim aliases1 As New Aliases() With {.Val = aliases}
    Dim autoredefine1 As New AutoRedefine() With {.Val = OnOffOnlyValues.Off}
    Dim basedon1 As New BasedOn() With {.Val = "Normal"}
    Dim linkedStyle1 As New LinkedStyle() With {.Val = "OverdueAmountChar"}
    Dim locked1 As New Locked() With {.Val = OnOffOnlyValues.Off}
    Dim primarystyle1 As New PrimaryStyle() With {.Val = OnOffOnlyValues.[On]}
    Dim stylehidden1 As New StyleHidden() With {.Val = OnOffOnlyValues.Off}
    Dim semihidden1 As New SemiHidden() With {.Val = OnOffOnlyValues.Off}
    Dim styleName1 As New StyleName() With {.Val = stylename}
    Dim nextParagraphStyle1 As New NextParagraphStyle() With { _
     .Val = "Normal"}
    Dim uipriority1 As New UIPriority() With {.Val = 1}
    Dim unhidewhenused1 As New UnhideWhenUsed() With { _
     .Val = OnOffOnlyValues.[On]}
    If aliases <> "" Then
        style.Append(aliases1)
    End If
    style.Append(autoredefine1)
    style.Append(basedon1)
    style.Append(linkedStyle1)
    style.Append(locked1)
    style.Append(primarystyle1)
    style.Append(stylehidden1)
    style.Append(semihidden1)
    style.Append(styleName1)
    style.Append(nextParagraphStyle1)
    style.Append(uipriority1)
    style.Append(unhidewhenused1)

    ' Create the StyleRunProperties object and specify some of the run properties.
    Dim styleRunProperties1 As New StyleRunProperties()
    Dim bold1 As New Bold()
    Dim color1 As New Color() With { _
     .ThemeColor = ThemeColorValues.Accent2}
    Dim font1 As New RunFonts() With { _
     .Ascii = "Lucida Console"}
    Dim italic1 As New Italic()
    ' Specify a 12 point size.
    Dim fontSize1 As New FontSize() With { _
     .Val = "24"}
    styleRunProperties1.Append(bold1)
    styleRunProperties1.Append(color1)
    styleRunProperties1.Append(font1)
    styleRunProperties1.Append(fontSize1)
    styleRunProperties1.Append(italic1)

    ' Add the run properties to the style.
    style.Append(styleRunProperties1)

    ' Add the style to the styles part.
    styles.Append(style)
End Sub

' Add a StylesDefinitionsPart to the document. Returns a reference to it.
Public Function AddStylesPartToPackage(ByVal doc As WordprocessingDocument) _
    As StyleDefinitionsPart
    Dim part As StyleDefinitionsPart
    part = doc.MainDocumentPart.AddNewPart(Of StyleDefinitionsPart)()
    Dim root As New Styles()
    root.Save(part)
    Return part
End Function

Contribute to this article

Want to edit or suggest changes to this content? You can edit and submit changes to this article using GitHub.

Show:
© 2016 Microsoft