Engineered for platform independence and convenience, GrapeCity Documents for Word (GcWord) is a high-performance Word API that offers a complete solution to work with Word documents in .NET Standard 2.0 applications. Generate, load, edit, and save Word documents in .NET Standard 2.0 with no dependencies on Microsoft Word! With a rich, intuitive object model, GcWord is easier to use than Microsoft’s API​.

With the Documents for Word API, you can:

  • Implement mail merge functionality in code
  • Use Word documents as templates to generate data-driven documents
  • Publish and securely share invoices, receipts, and project plans
  • Export documents to PDF
  • Create bibliographies, resumes, journals, flyers, newsletters, and more

In another article, we discuss how to get started with Documents for Word on Windows, Mac and Linux. This blog guides you through how to use GcWord to create Word documents in code.

Step 1: Install the GcWord API

Prerequisites

GcWord can be used in any application that targets .NET Standard 2.0 (including .NET Core, .NET FrameWork, Mono and Xamarin).

  1. Install .NET Core.
  2. Create a .NET Core Console Application in Visual Studio, or just use the dotnet CLI (command line interface).

dotnet new console

  • Add GcWord package.

You can install the GcWord NuGet package using Visual Studio or the dotnet CLI.

Install using Visual Studio

  1. Right-click your project file and click "Manage NuGet Packages."
  2. On the Browse tab, at the top right, set the package source to nuget.org.
  3. In the Search box, type GrapeCity.Documents.
  4. Choose GrapeCity.Documents.Word and Install.

Install using dotnet CLI

  1. Open a cmd window under your project folder.
  2. Execute this command:

dotnet add package GrapeCity.Documents.Word

Step 2: Set up your project

Add namespaces

  1. Open the Program.cs file from your project folder.
  2. Paste following namespace to use GcWord classes.

using GrapeCity.Documents.Word;

Step 3: Create a new GcWord document

In the Program.cs file's Main method, paste the following line of code between the braces. This creates a new document by calling the GcWordDocument class.

GcWordDocument doc = new GcWordDocument();

Step 4: Add titles to the document

We'll use the GcWord object model to create sections of a Word document. Before we start, let's look at the GcWord architecture.

  1. The main body of a Word document is split into different sections, and you can add paragraphs to different sections of the document. You can access the sections using doc.Body.Sections.

    To add a title, first, get the range of the first section. Then write the code to add a paragraph that contains title text to the first section of the document. In addition, set the alignment of the title to the center of the document.

// Add the first title to the document:
// The primary way of manipulating objects in GcWord is via ranges. 
//Get the range of first section of the document body in which we will add title to the document.
Range range = doc.Body.Sections.First.GetRange();
Paragraph p = range.Paragraphs.Add("Introduction");
p.Format.Alignment = ParagraphAlignment.Center;
  1. Next, get the range of the paragraph that we've just added to set properties of the title.

Range r = p.GetRange();

  1. A run is a contiguous fragment of text within a paragraph with a uniform formatting. In order to change font, size or other text properties, you can use direct formatting: access the run of text you want to change, and set properties on its font. (An alternative is to change the character style associated with a run, as shown later.) Write the following code to get the first run in the paragraph range and set properties:
Run run = r.Runs.First;
run.Font.Size = 20;
run.Font.Name = "Arial";
  1. Next, add another title below the first, and set similar properties:
p = range.Paragraphs.Add("The Importance of Wetlands");
p.Format.Alignment = ParagraphAlignment.Center;
r = p.GetRange();
run = r.Runs.Last;
run.Font.Size = 16;
run.Font.Name = "Arial";

Step 5: Add the rest of the paragraphs to the document

Set paragraph style

Add the following code to set the style for the rest of the paragraphs in the document:

var pStyle = doc.Styles.Add("par style 1", StyleType.Paragraph);
pStyle.ParagraphFormat.Indentation.FirstLineIndent = 36;
pStyle.ParagraphFormat.Alignment = ParagraphAlignment.Distribute;

Set character style

This code sets the character style for characters in the rest of the document:

var cStyle = doc.Styles.Add("char style 1", StyleType.Character);
cStyle.Font.Size = 9;

Get text from a text file and add paragraphs to the document

The code gets the paragraphs from a text file and adds them to the paragraph object of GcWord. Then it sets similar properties to align the paragraphs as "Distribute" and sets the font size to a smaller font:

//Get text for paragraphs from a text file
string line;
int counter = 0;
System.IO.StreamReader file = new System.IO.StreamReader(@"TheImportanceOfWetlands.txt");
//Add a paragraph and set paragraph style on it
p = doc.Body.Sections.First.GetRange().Paragraphs.Add();
p.Style = pStyle;
//Read the text file line by line and add to the last run in the document
while ((line = file.ReadLine()) != null && line != @"\n")
{
      if (string.IsNullOrEmpty(line))
      {
           p = doc.Body.Sections.First.GetRange().Paragraphs.Add();
           p.Style = pStyle;
      }
      run = p.GetRange().Runs.Add(line);
      run.Style = cStyle;
      counter++;
}

Step 6: Save the document to .docx file

Save the document to .docx file:

doc.Save("ImportanceOfWetlands.docx", DocumentType.Document);

Your document looks like this:

How to Generate Word Documents in Code

Download the sample for generating Word docs in code

What do you think about using GrapeCity's Word library in .NET applications? Do you have any special use cases? Leave us a comment below!

Generate Word Documents in Code

Download GrapeCity Documents for Word

Download Now!