News Category

Document Operation

Document Operation (25)

In our daily work, we often meet the requirements to copy parts or the whole content (without header or footer) from one Word document to another. It's an easy task if we use copy and paste function.

However, how could we achieve this task programmatically? This article is aimed to introduce the method of how to transfer the whole content from source document to target document using Spire.Doc. If you only want to transfer several paragraphs, please refer to this article.

Source Document:

Copy Content from one Word Document to another in C#, VB.NET

Target Document:

Copy Content from one Word Document to another in C#, VB.NET

Code Snippet:

Step 1: Initialize a new object of Document class and load the source document.

Document sourceDoc = new Document("source.docx");

Step 2: Initialize another object to load target document.

Document destinationDoc = new Document("target.docx");

Step 3: Copy content from source file and insert them to the target file.

foreach (Section sec in sourceDoc.Sections) 
{
    foreach (DocumentObject obj in sec.Body.ChildObjects)
    {
        destinationDoc.Sections[0].Body.ChildObjects.Add(obj.Clone());
    }
}

Step 4: Save the changes.

destinationDoc.SaveToFile("target.docx", FileFormat.Docx2010);

Result:

Copy Content from one Word Document to another in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
namespace CopyContent
{
    class Program
    {
        static void Main(string[] args)
        {
            Document sourceDoc = new Document("source.docx");
            Document destinationDoc = new Document("target.docx");
            foreach (Section sec in sourceDoc.Sections)
            {
                foreach (DocumentObject obj in sec.Body.ChildObjects)
                {
                    destinationDoc.Sections[0].Body.ChildObjects.Add(obj.Clone());
                }
            }
            destinationDoc.SaveToFile("target.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("target.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc
Namespace CopyContent
	Class Program
		Private Shared Sub Main(args As String())
			Dim sourceDoc As New Document("source.docx")
			Dim destinationDoc As New Document("target.docx")
			For Each sec As Section In sourceDoc.Sections
				For Each obj As DocumentObject In sec.Body.ChildObjects
					destinationDoc.Sections(0).Body.ChildObjects.Add(obj.Clone())
				Next
			Next
			destinationDoc.SaveToFile("target.docx", FileFormat.Docx2010)
			System.Diagnostics.Process.Start("target.docx")
		End Sub
	End Class
End Namespace

Nowadays, we're facing a bigger chance to download a file from URL since more documents are electronically delivered by internet. In this article, I'll introduce how to download a Word document from URL programmatically using Spire.Doc in C#, VB.NET.

Spire.Doc does not provide a method to download a Word file directly from URL. However, you can download the file from URL into a MemoryStream and then use Spire.Doc to load the document from MemoryStream and save as a new Word document to local folder.

Code Snippet:

Step 1: Initialize a new Word document.

Document doc = new Document();

Step 2: Initialize a new instance of WebClient class.

WebClient webClient = new WebClient();

Step 3: Call WebClient.DownloadData(string address) method to load the data from URL. Save the data to a MemoryStream, then call Document.LoadFromStream() method to load the Word document from MemoryStream.

using (MemoryStream ms = new MemoryStream(webClient.DownloadData("http://www.e-iceblue.com/images/test.docx")))
{
    doc.LoadFromStream(ms,FileFormat.Docx);
}

Step 4: Save the file.

doc.SaveToFile("result.docx",FileFormat.Docx);

Run the program, the targeted file will be downloaded and saved as a new Word file in Bin folder.

How to Download a Word Document from URL in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using System.IO;
using System.Net;

namespace DownloadfromURL
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            WebClient webClient = new WebClient();
            using (MemoryStream ms = new MemoryStream(webClient.DownloadData("http://www.e-iceblue.com/images/test.docx")))
            {
                doc.LoadFromStream(ms, FileFormat.Docx);
            }
            doc.SaveToFile("result.docx", FileFormat.Docx);
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports System.IO
Imports System.Net
Namespace DownloadfromURL
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			Dim webClient As New WebClient()
Using ms As New MemoryStream(webClient.DownloadData("http://www.e-iceblue.com/images/test.docx"))
				doc.LoadFromStream(ms, FileFormat.Docx)
			End Using
			doc.SaveToFile("result.docx", FileFormat.Docx)

		End Sub
	End Class
End Namespace

Sometimes in word files, we type another language rather than default, and need spellers and other proofing tools adjust to the language we typed.

This article is talking about how to alter language dictionary as non-default language via Spire.Doc. Here take English as default language and alter to Spanish in Peru as an example.

As for more language information, refer this Link to Microsoft Locale ID Values.

Here are the steps:

Step 1: Create a new word document.

Document document = new Document();

Step 2: Add new section and paragraph to the document.

Section sec = document.AddSection();
Paragraph para = sec.AddParagraph();

Step 3: Add a textRange for the paragraph and append some Peru Spanish words.

TextRange txtRange = para.AppendText("corrige según diccionario en inglés");
txtRange.CharacterFormat.LocaleIdASCII = 10250;

Step 4: Save and review.

document.SaveToFile("result.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("result.docx");

Here is the result screenshot.

How to alter Language dictionary via Spire.Doc

Full Code:

using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace AlterLang
{

    class Program
    {

        static void Main(string[] args)
        {
            Document document = new Document();
            Section sec = document.AddSection();
            Paragraph para = sec.AddParagraph();
            TextRange txtRange = para.AppendText("corrige según diccionario en inglés");
            txtRange.CharacterFormat.LocaleIdASCII = 10250;
            document.SaveToFile("result.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("result.docx");
        }
    }
}

When you type in a document, Word automatically counts the number of pages and words in your document and displays them on the status bar – Word Count, at the bottom of the workspace. But how can we get the number of words, characters in an existing Word document through programming? This article aims to give you a simple solution offered by Spire.Doc.

Test file:

Count the number of words in a document in C#, VB.NET

Detailed Steps for Getting the Number of Words and Characters

Step 1: Create a new instance of Spire.Doc.Document class and load the test file.

Document doc = new Document();
doc.LoadFromFile("test.docx", FileFormat.Docx2010);

Step 2: Display the number of words, characters including or excluding spaces on console.

Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount);
Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace);
Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount);

Output:

Count the number of words in a document in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using System;
namespace CountNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("test.docx", FileFormat.Docx2010);
            Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount);
            Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace);
            Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount);
            Console.ReadKey();
        }
    }
}
[VB.NET]
Imports Spire.Doc
Namespace CountNumber
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("test.docx", FileFormat.Docx2010)
			Console.WriteLine("CharCount: " + doc.BuiltinDocumentProperties.CharCount)
			Console.WriteLine("CharCountWithSpace: " + doc.BuiltinDocumentProperties.CharCountWithSpace)
			Console.WriteLine("WordCount: " + doc.BuiltinDocumentProperties.WordCount)
			Console.ReadKey()
		End Sub
	End Class
End Namespace

When dealing with Word documents, sometimes developers need to merge multiple files into a single file. Spire.Doc, especially designed for developers enables you to manipulate doc files easily and flexibly.

There is already a document introducing how to merge doc files. Check it here:

.NET Merge Word - Merge Multiple Word Documents into One in C# and VB.NET

Using the method above, you have to copy sections one by one. But the new method just concatenates them. It has improved and is very easy to use

Step 1: Load the original word file "A Good Man.docx".

document.LoadFromFile("A Good Man.docx", FileFormat.Docx);

Step 2: Merge another word file "Original Word.docx" to the original one.

document.InsertTextFromFile("Original Word.docx", FileFormat.Docx);

Step 3: Save the file.

document.SaveToFile("MergedFile.docx", FileFormat.Docx);

Full code and screenshot:

static void Main(string[] args)
{
    Document document = new Document();
    document.LoadFromFile("A Good Man.docx", FileFormat.Docx);

    document.InsertTextFromFile("Original Word.docx", FileFormat.Docx);

    document.SaveToFile("MergedFile.docx", FileFormat.Docx);
    System.Diagnostics.Process.Start("MergedFile.docx");
}

Full code and screenshot:

using Spire.Doc;
namespace MergeWord
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("A Good Man.docx", FileFormat.Docx);

            document.InsertTextFromFile("Original Word.docx", FileFormat.Docx);

            document.SaveToFile("MergedFile.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("MergedFile.docx");
        }
    }
}

New Method to Merge Word Documents

Document properties (also known as metadata) are a set of information about a document. All Word documents come with a set of built-in document properties, including title, author name, subject, keywords, etc. In addition to the built-in document properties, Microsoft Word also allows users to add custom document properties to Word documents. In this article, we will explain how to add these document properties to Word documents in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Add Built-in Document Properties to a Word Document in C# and VB.NET

A built-in document property consists of a name and a value. You cannot set or change the name of a built-in document property as it's predefined by Microsoft Word, but you can set or change its value. The following steps demonstrate how to set values for built-in document properties in a Word document:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the built-in document properties of the document through Document.BuiltinDocumentProperties property.
  • Set values for specific document properties such as title, subject and author through Title, Subject and Author properties of BuiltinDocumentProperties class.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;

namespace BuiltinDocumentProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Add built-in document properties to the document
            BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
            standardProperties.Title = "Add Document Properties";
            standardProperties.Subject = "C# Example";
            standardProperties.Author = "James";
            standardProperties.Company = "Eiceblue";
            standardProperties.Manager = "Michael";
            standardProperties.Category = "Document Manipulation";
            standardProperties.Keywords = "C#, Word, Document Properties";
            standardProperties.Comments = "This article shows how to add document properties";

            //Save the result document
            document.SaveToFile("StandardDocumentProperties.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Add Document Properties to Word Documents

Add Custom Document Properties to a Word Document in C# and VB.NET

A custom document property can be defined by a document author or user. Each custom document property should contain a name, a value and a data type. The data type can be one of these four types: Text, Date, Number and Yes or No. The following steps demonstrate how to add custom document properties with different data types to a Word document:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the custom document properties of the document through Document.CustomDocumentProperties property.
  • Add custom document properties with different data types to the document using CustomDocumentProperties.Add(string, object) method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using System;

namespace CustomDocumentProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Add custom document properties to the document
            CustomDocumentProperties customProperties = document.CustomDocumentProperties;
            customProperties.Add("Document ID", 1);
            customProperties.Add("Authorized", true);
            customProperties.Add("Authorized By", "John Smith");
            customProperties.Add("Authorized Date", DateTime.Today);

            //Save the result document
            document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Add Document Properties to Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

C#/VB.NET: Merge Word Documents

2022-12-05 08:06:00 Written by support iceblue

Long papers or research reports are often completed collaboratively by multiple people. To save time, each person can work on their assigned parts in separate documents and then merge these documents into one after finish editing. Apart from manually copying and pasting content from one Word document to another, this article will demonstrate the following two ways to merge Word documents programmatically using Spire.Doc for .NET .

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Merge Documents by Inserting the Entire File

The Document.InsertTextFromFile() method provided by Spire.Doc for .NET allows merging Word documents by inserting other documents entirely into a document. Using this method, the contents of the inserted document will start from a new page. The detailed steps are as follows:

  • Create a Document instance.
  • Load the original Word document using Document.LoadFromFile() method.
  • Insert another Word document entirely to the original document using Document.InsertTextFromFile() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;

namespace MergeWord
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance 
            Document document = new Document();

            //Load the original Word document
            document.LoadFromFile("Doc1.docx", FileFormat.Docx);

            //Insert another Word document entirely to the original document
            document.InsertTextFromFile("Doc2.docx", FileFormat.Docx);

            //Save the result document
            document.SaveToFile("MergedWord.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Merge Word Documents

Merge Documents by Cloning Contents

If you want to merge documents without starting a new page, you can clone the contents of other documents to add to the end of the original document. The detailed steps are as follows:

  • Load two Word documents.
  • Loop through the second document to get all the sections using Document.Sections property, and then loop through all the sections to get their child objects using Section.Body.ChildObjects property.
  • Get the last section of the first document using Document.LastSection property, and then add the child objects to the last section of the first document using LastSection.Body.ChildObjects.Add() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;

namespace MergeWord
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load two Word documents
            Document doc1 = new Document("Doc1.docx");
            Document doc2 = new Document("Doc2.docx");

            //Loop through the second document to get all the sections
            foreach (Section section in doc2.Sections)
            {

                //Loop through the sections of the second document to get their child objects
                foreach (DocumentObject obj in section.Body.ChildObjects)
                {

                    // Get the last section of the first document
                     Section lastSection = doc1.LastSection;

                    //Add all child objects to the last section of the first document
                    lastSection.Body.ChildObjects.Add(obj.Clone());
                }
            }

            // Save the result document
            doc1.SaveToFile("MergeDocuments.docx", FileFormat.Docx);
        }
    }
} 

C#/VB.NET: Merge Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Users can change Word view mode according to own reading habit. This guide introduces a solution to set Word view modes in C# and VB.NET.

There are several Word View Modes provided with customers, including Print Layout, Web Layout, Full Screen, Draft, Outline and Zoom in/out with specified percentage. The view mode can be selected when opening to make the document to be presented to match readers’ reading habit. This guide focuses on demonstrating how to set Word view mode in C# and VB.NET via Spire.Doc for .NET. The screenshot presents the result after setting Word view mode.

Word Document Properties

Spire.Doc for .NET, specializing in operating Word in .NET, offers a ViewSetup class to enable users to set Word view modes through assigning specified values for its properties. In this example, the Word view modes will be set as Web Layout with zoom out 150 percent. Therefore, the set properties of ViewSetup class include DocumentViewType, ZoomPercent and ZoomType.

DocumentViewTyp: There are five types provided by Spire.Doc for .NET: None, NormalLayout, OutlineLayout, PrintLayout and WebLayout.

ZoomPercent: The default ZoomPercent is 100. User can set other percent according to requirements. In this example, ZoomPercent is set as 150.

ZoomType: There are four zoom types provided by Spire.Doc for .NET: Full Page to automatically recalculate zoom percentage to fit one full page; None to use the explicit zoom percentage; PageWidth to automatically recalculate zoom percentage to fit page width; TextFit to automatically recalculate zoom percentage to fit text. Because the zoom percentage is set as 150, so the ZoomType is set as None in this example.

Download and install Spire.Doc for .NET and follow the code:

[C#]
using Spire.Doc;

namespace WordViewMode
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile(@"E:\Work\Documents\WordDocuments\.NET Framework.docx");

            doc.ViewSetup.DocumentViewType = DocumentViewType.WebLayout;
            doc.ViewSetup.ZoomPercent = 150;
            doc.ViewSetup.ZoomType = ZoomType.None;

            doc.SaveToFile("WordViewMode.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("WordViewMode.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc

Namespace WordViewMode
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            Dim doc As New Document()
            doc.LoadFromFile("E:\Work\Documents\WordDocuments\.NET Framework.docx")

            doc.ViewSetup.DocumentViewType = DocumentViewType.WebLayout
            doc.ViewSetup.ZoomPercent = 150
            doc.ViewSetup.ZoomType = ZoomType.None

            doc.SaveToFile("WordViewMode.docx", FileFormat.Docx2010)
            System.Diagnostics.Process.Start("WordViewMode.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, professional Word component, is specially designed for developers to fast generate, write, modify and save Word documents in .NET, Silverlight and WPF with C# and VB.NET. Also, it supports conversion between Word and other popular formats, such as PDF, HTML, Image, Text and so on, in .NET and WPF platform.

Edit Word Document in C#, VB.NET

2010-12-16 06:35:29 Written by Administrator

In order to correct wrong spellings or add some new contents in a Word document, users need to edit an existing Word document. This guide demonstrates a solution to edit Word document in C# and VB.NET.

Spire.Doc for .NET, wonderful .NET Word component, offers a Paragraph class, which enables users to edit contents in paragraphs through set its properties. In this example, the title is updated and new text is added in paragraph two (Title is paragraph one). The editing result is shown as following screenshot.

Edit Word Document

Firstly, declare a Paragraph instance and its value is set as paragraph one (title). Set its Text property to update the original contents. Secondly, declare another Paragraph instance and its value is set as Paragraph two. Invoke Paragraph.AppendText method to add new contents for this paragraph. The overload passed to this method is string text. For distinguishing new contents and existing contents, new contents are formatted in this example. Declare a TextRange instance and set its value as new added contents. Set CharacterFormat properties for this TextRange, including FontName, FontSize and TextColor. Download and install Spire.Doc for .NET and follow the code below to edit Word document.

[C#]
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace EidtWord
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx");

            //Update Text of Title
            Section section = document.Sections[0];
            Paragraph para1 = section.Paragraphs[0];
            para1.Text = "Spire.Doc for .NET Introduction";

            //Add New Text
            Paragraph para2 = section.Paragraphs[1];
            TextRange tr=para2.AppendText("Spire.Doc for .NET is stand-alone"
            +"to enables developers to operate Word witout Microsoft Word installed.");
            tr.CharacterFormat.FontName = "Cataneo BT";
            tr.CharacterFormat.FontSize=12;
            tr.CharacterFormat.TextColor = Color.YellowGreen;
           
            //Save and Launch
            document.SaveToFile("Edit Word.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Edit Word.docx");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace EidtWord
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx")

            'Update Text of Title
            Dim section As Section = document.Sections(0)
            Dim para1 As Paragraph = section.Paragraphs(0)
            para1.Text = "Spire.Doc for .NET Introduction"

            'Add New Text
            Dim para2 As Paragraph = section.Paragraphs(1)
            Dim tr As TextRange = para2.AppendText("Spire.Doc for .NET is stand-alone" &
                                                   "to enables developers to operate Word witout Microsoft Word installed.")
            tr.CharacterFormat.FontName = "Cataneo BT"
            tr.CharacterFormat.FontSize = 12
            tr.CharacterFormat.TextColor = Color.YellowGreen

            'Save and Launch
            document.SaveToFile("Edit Word.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("Edit Word.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, an easy-to-use component to operate Word document, allows developers to fast generate, write, edit and save Word (Word 97-2003, Word 2007, Word 2010) in C# and VB.NET for .NET, Silverlight and WPF.

C#/VB.NET: Create a Word Document

2022-05-31 08:33:00 Written by Administrator

There's no doubt that Word document is one of the most popular document file types today. Because Word document is an ideal file format for generating letters, memos, reports, term papers, novels and magazines, etc. In this article, you will learn how to create a simple Word document from scratch in C# and VB.NET by using Spire.Doc for .NET.

Spire.Doc for .NET provides the Document class to represent a Word document model, allowing users to read and edit existing documents or create new ones. A Word document must contain at least one section (represented by Section class) and each section is a container for basic Word elements like paragraphs, tables, headers, footers and so on. The table below lists the important classes and methods involved in this tutorial.

Member Description
Document class Represents a Word document model.
Section class Represents a section in a Word document.
Paragraph class Represents a paragraph in a section.
ParagraphStyle class Defines the font formatting information that can be applied to a paragraph.
Section.AddParagraph() method Adds a paragraph to a section.
Paragraph.AppendText() method Appends text to a paragraph at the end.
Paragraph.ApplyStyle() method Applies a style to a paragraph.
Document.SaveToFile() method Saves the document to a Word file with an extension of .doc or .docx. This method also supports saving the document to PDF, XPS, HTML, PLC, etc.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Create a Simple Word Document

The following are the steps to create a simple Word document that contains several paragraphs by using Spire.Doc for .NET.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Set the page margins through Section.PageSetUp.Margins property.
  • Add several paragraphs to the section using Section.AddParagraph() method.
  • Add text to the paragraphs using Paragraph.AppendText() method.
  • Create a ParagraphStyle object, and apply it to a specific paragraph using Paragraph.ApplyStyle() method.
  • Save the document to a Word file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace CreateWordDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();

            //Add a section
            Section section = doc.AddSection();

            //Set the page margins
            section.PageSetup.Margins.All = 40f;

            //Add a paragraph as title
            Paragraph titleParagraph = section.AddParagraph();
            titleParagraph.AppendText("Introduction of Spire.Doc for .NET");

            //Add two paragraphs as body
            Paragraph bodyParagraph_1 = section.AddParagraph();
            bodyParagraph_1.AppendText("Spire.Doc for .NET is a professional Word.NET library specifically designed " +
                "for developers to create, read, write, convert, compare and print Word documents on any.NET platform " +
                "(.NET Framework, .NET Core, .NET Standard, Xamarin & Mono Android) with fast and high-quality performance.");


            Paragraph bodyParagraph_2 = section.AddParagraph();
            bodyParagraph_2.AppendText("As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to " +
                         "be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
                         "document creation capabilities into any developers' .NET applications.");

            //Create a style for title paragraph
            ParagraphStyle style1 = new ParagraphStyle(doc);
            style1.Name = "titleStyle";
            style1.CharacterFormat.Bold = true;
            style1.CharacterFormat.TextColor = Color.Purple;
            style1.CharacterFormat.FontName = "Times New Roman";
            style1.CharacterFormat.FontSize = 12;
            doc.Styles.Add(style1);
            titleParagraph.ApplyStyle("titleStyle");

            //Create a style for body paragraphs
            ParagraphStyle style2 = new ParagraphStyle(doc);
            style2.Name = "paraStyle";
            style2.CharacterFormat.FontName = "Times New Roman";
            style2.CharacterFormat.FontSize = 12;
            doc.Styles.Add(style2);
            bodyParagraph_1.ApplyStyle("paraStyle");
            bodyParagraph_2.ApplyStyle("paraStyle");

            //Set the horizontal alignment of paragraphs
            titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
            bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
            bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;

            //Set the first line indent 
            bodyParagraph_1.Format.FirstLineIndent = 30;
            bodyParagraph_2.Format.FirstLineIndent = 30;

            //Set the after spacing
            titleParagraph.Format.AfterSpacing = 10;
            bodyParagraph_1.Format.AfterSpacing = 10;

            //Save to file
            doc.SaveToFile("WordDocument.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Create a Word Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Page 2 of 2