Skip to main content Skip to footer

Add Paragraph and Character formatting in a Word document in .NET Core

GrapeCity Documents for Word (GcWord) is a Word API that offers a complete solution for working with Word documents in .NET Core. With an object model based on the Microsoft Office API, Word JavaScript API, and OpenXML SDK, you can create, load, edit, save, and convert Word documents in .NET Core-with zero dependencies on Microsoft Word.

In this video, we'll walk through adding a paragraph of text using GcWord. We'll also add character formatting to different parts of the paragraph.

Steps:

Make sure you have necessary namespaces included in your project.

In this example, we'll use a combination of a set of random words from the util-dot-cs file.

  • First, copy a paragraph of text.

  • Create a GcWordDocument object.

  • Add the paragraph to the first section range of the Document's body.

The primary way to manipulate objects in GcWord is using ranges. Get the range on the paragraph that we've just added.

A Run is a contiguous fragment of a document with uniform formatting. In our case, we have only one run so far, so get that run.

  • Set the size of the font on the whole run.

  • Text represents a contiguous fragment of text. It also belongs to a Run, and cannot span multiple runs, although a run can contain several Texts. Get the text object.

  • Split the text into two halves. Here, the split method returns the 2nd part.

At this point, our run contains two texts, or two halves of the original text. We'll now split the run into two corresponding runs so that we can apply different formatting to the two texts.

The text was split into two halves, but the first half can still be accessed via the text variable. A text's containing run can always be accessed via ParentRun.

  • We set the font of the first half to italic and the font of the second half to Red forecolor.

  • Save the Word file.

  • Run the project and the Word file is generated in your project.

  • Open the Word file.

  • The first half of paragraph is italic, while second half is red in forecolor.

In another video, we demonstrate how to convert Word Documents to PDF in .NET apps.

Shilpa Sharma - Product Manager

Shilpa Sharma

Product Manager
comments powered by Disqus