Friday, 14 March 2014 07:48

New Method to Merge Word Documents

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

Published in Document Operation

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.

Published in Document Operation
Monday, 05 December 2022 08:06

C#/VB.NET: Merge Word Documents

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.

Published in Document Operation
Wednesday, 16 January 2013 01:39

Set Word View Modes in C#, VB.NET

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.

Published in Document Operation
Wednesday, 08 May 2024 03:21

C#: Mail Merge in Word Documents

Mail Merge is a powerful feature in Microsoft Word that allows you to create multiple documents such as letters, labels, envelopes, and even e-mails from a single template document and a data source. It's particularly useful for tasks like sending personalized correspondence to a large number of recipients without having to write each letter individually.

In this article, you will learn how to perform a mail merge in a Word document 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

Understanding the Components of Mail Merge

  • Main Document: This is the template file where you design your letter, label, or other types of documents with placeholders (also known as merge fields) that will be filled in by data from the data source.
  • Data Source: This is the spreadsheet or database containing the information you want to use to populate your main document. It can be an Excel sheet, Access database, CSV file, XML file or even a simple text file.
  • Merge Fields: These are placeholders in the main document that will be replaced with data from the corresponding record in the data source.

Create a Template Word Document

To generate a template Word document with merge fields, it’s recommended that you use Word editors such as Microsoft Word. The visual interface of the Word editor allows you to design a unique layout, formatting, and other elements interactively for your template.

The following screenshot shows the addition of merge fields to a Word document using MS Word. Remember to use the "Image:FieldName" format if you want to merge an image into a merge field.

C#: Mail Merge in Word Documents

If you wish to create a template Word document using C# code, you can follow these steps.

  • Create a Document object.
  • Add a section.
  • Add a paragraph to the section.
  • Add merge fields to the paragraph using Paragraph.AppendField() method.
  • Save the document to a Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

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

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

            // Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            // Add text and mail merge fields to the paragraph
            paragraph.AppendText("Full Name: ");
            paragraph.AppendField("Name", FieldType.FieldMergeField);
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendText("Email Address: ");
            paragraph.AppendField("Email", FieldType.FieldMergeField);
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendText("Avatar: ");
            paragraph.AppendField("Image:Avatar", FieldType.FieldMergeField);

            // Save the document
            document.SaveToFile("Template.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }
    }
}

Simple Mail Merge in a Word Document

Spire.Doc offers the MailMerge.Execute() method to perform the specified mail merge operation in a Word document. This method has 6 overloads allowing users to perform a mail merge from different data sources, such as DataTable, DataView, and string arrays.

The steps to perform a mail merge using data provided in arrays are as follows.

  • Create a Document object.
  • Load a template Word document from a specified file path.
  • Define an array to hold the field names.
  • Define an array to hold the values that will be used to fill the fields
  • Mail merge data into the fields using MailMerge.Execute() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Reporting;
using System.Drawing;

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

            // Load the template Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Specify field names
            String[] fieldNames = {

                "Name",
                "Email",
                "Avatar"
            };

            // Specify values that'll be used to fill the fields
            String[] fieldValues = {

                "John Smith",
                "john.smith@e-iceblue.com",
                "C:\\Users\\Administrator\\Desktop\\avatar.png"
            };

            // Register an event which occurs when merging the image filed
            document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);

            // Mail merge data to the document  
            document.MailMerge.Execute(fieldNames, fieldValues);

            // Save the document  
            document.SaveToFile("MailMerge.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }

        // Fill an image field with a picture
        private static void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field)
        {
            string filePath = field.FieldValue as string;

            if (!string.IsNullOrEmpty(filePath))
            {
                field.Image = Image.FromFile(filePath);
            }
        }
    }
}

C#: Mail Merge in Word Documents

Mail Merge with a Region

A region refers to a specific area within a document where you want to insert data from your data source. Mail Merge will repeat that region for each record in the data source. Spire.Doc offers the MailMerge.ExecuteWidthRegion() method to execute mail merge with a region.

The steps to perform a mail merge with a region using the data provided by a DataTable are as follows.

  • Create a Document object.
  • Load a template Word document from a specified file path.
  • Create a DataTable object, which will be used as the data source.
  • Execute mail merge with the region using MailMerge.ExecuteWidthRegion() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using System.Data;

namespace MailMergeWithGroup
{
    class Program
    {
        static void Main(string[] args)
        {

            // Create a Document object
            Document document = new Document();

            // Load a template Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Create a datatable, specifying table name
            DataTable table = new DataTable("Employee");

            // Add sample data to table
            table.Columns.Add("Name");
            table.Columns.Add("Address");
            table.Columns.Add("City");
            table.Rows.Add("John Doe", "123 Main St", "New York");
            table.Rows.Add("Jane Smith", "456 Elm St", "Los Angeles");
            table.Rows.Add("Bob Johnson", "789 Oak St", "Chicago");

            // Mail merge within the region
            document.MailMerge.ExecuteWidthRegion(table);

            // Save the document  
            document.SaveToFile("MailMergeWithRegion.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }
    }
}

C#: Mail Merge in Word Documents

Mail Merge with Nested Regions

Mail merge for nested groups works by replacing merge fields within nested regions with data that is organized in a hierarchical structure. Nested regions allow you to create more complex layouts where the content of one region depends on the data in another region.

The steps to perform a mail merge with nested regions using the data from an XML file are as follows.

  • Create a Document object.
  • Load a template Word document from a specified file path.
  • Read data from an XML file to a DataSet object.
  • Create a List<DictionaryEntry> object to store the merge field information.
  • Create DicitionaryEntry objects and add them to the list, which specify the merge field names and associated expressions.
  • Execute mail merge with the nested regions using MailMerge.ExecuteWidthNestedRegion() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using System.Collections;
using System.Data;

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

            // Load a template Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Read data from an XML file to a DataSet object
            DataSet dataSet = new DataSet();
            dataSet.ReadXml("C:\\Users\\Administrator\\Desktop\\Orders.xml");

            // Create a List object to store the merge field information
            List list = new List();

            // Create two DicitionaryEntry objects and add them to the list (each object specifies the merge field name and associated expression)
            DictionaryEntry dictionaryEntry = new DictionaryEntry("Customer", string.Empty);
            list.Add(dictionaryEntry);

            dictionaryEntry = new DictionaryEntry("Order", "Customer_Id = %Customer.Customer_Id%");
            list.Add(dictionaryEntry);

            // Perform the mail merge operation with the nested region
            document.MailMerge.ExecuteWidthNestedRegion(dataSet, list);

            // Save to file
            document.SaveToFile("MailMergeWithNestedRegions.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }
    }
}

C#: Mail Merge in 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.

Published in Mail Merge
Thursday, 08 August 2024 06:35

C#: Edit Word Documents

Editing a Word document is necessary when you want to improve readability, correct errors, refine formatting, maintain consistency, adapt content, facilitate collaboration, and optimize the document for any other purposes. Programmatically editing a Word document using C# can be a powerful approach to automate document processing and manipulation tasks.

In this article, you will learn how to edit a Word document using C# and the Spire.Doc for .NET library.

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

Modify Text in a Word Document in C#

Spire.Doc allows you to programmatically access specific sections and paragraphs in Word documents. To retrieve a particular section, use the Document.Sections[index] property. Then, to get a particular paragraph within that section, leverage the Section.Paragraphs[index] property. Finally, you can update the text content of the paragraph using the Paragraph.Text property.

The steps to modify text in a Word document using C# are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Get a specific paragraph through Section.Paragraphs[index] property.
  • Reset the text of the paragraph through Paragraph.Text property.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

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

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get a specific section
            Section section = document.Sections[0];

            // Get a specific paragraph
            Paragraph paragraph = section.Paragraphs[0];

            // Modify the text of the paragraph 
            paragraph.Text = "Updated Title";

            // Save the document to a different Word file
            document.SaveToFile("ModifyText.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

C#: Edit Word Documents

Change Formatting of Text in a Word Document in C#

To change the text formatting within a paragraph, first obtain the paragraph object, then iterate through its child objects to locate the individual text ranges. For each text range, you can reset the formatting using the CharacterFormat property of the TextRange.

The steps to change text formatting in a Word document are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Get a specific paragraph through Section.Paragraphs[index] property.
  • Iterate through the child objects in the paragraph.
    • Determine if a child object is a text range.
    • Get a specific text range.
    • Reset the text formatting through TextRange.CharacterFormat property.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace ChangeTextFont
{
    class Program
    {
        static void Main(string[] args)
        {

            // Create a new document object
            Document document = new Document();

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get a specific section
            Section section = document.Sections[0];

            // Get a specific paragraph
            Paragraph paragraph = section.Paragraphs[2];

            // Iterate through the child objects in the paragraph
            for (int i = 0; i < paragraph.ChildObjects.Count; i++)
            {

                // Determine if a child object is text range
                if (paragraph.ChildObjects[i] is TextRange)
                {
                    // Get a specific text range
                    TextRange textRange = (TextRange)paragraph.ChildObjects[i];

                    // Reset font name for it
                    textRange.CharacterFormat.FontName = "Corbel Light";

                    // Reset font size for it
                    textRange.CharacterFormat.FontSize = 11;

                    // Reset text color for it
                    textRange.CharacterFormat.TextColor = Color.Blue;

                    // Apply italic to the text range 
                    textRange.CharacterFormat.Italic = true;
                }
            }

            // Save the document to a different Word file
            document.SaveToFile("ChangeFont.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

C#: Edit Word Documents

Add New Elements to a Word Document in C#

In addition to modifying the existing content in a Word document, you can also insert various types of new elements, such as text, images, tables, lists, and charts. As most elements are paragraph-based, you have the flexibility to add a new paragraph at the end of the document or insert it mid-document. You can then populate this new paragraph with the desired content, whether that's plain text, images, or other elements.

Below are the steps to add new elements (text and images) to a Word document using C#:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Add a paragraph to the section using Section.AddParagraph() method.
  • Add text to the paragraph using Paragraph.AppendText() method.
  • Add an image to the paragraph using Paragraph.AppendPicture() method.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

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

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

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

            // Add a paragraph to the section
            Paragraph paragraph = lastSection.AddParagraph();

            // Add text to the paragraph
            paragraph.AppendText("This text and the image shown below are added programmatically using C# and Spire.Doc for .NET.");

            // Add an image to the paragraph
            paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\logo.png");

            // Create a paragraph style
            ParagraphStyle style = new ParagraphStyle(document);
            style.Name = "FontStyle";
            style.CharacterFormat.FontName = "Times New Roman";
            style.CharacterFormat.FontSize = 12;
            document.Styles.Add(style);

            // Apply the style to the paragraph
            paragraph.ApplyStyle(style.Name);

            // Save the document to a different Word file
            document.SaveToFile("AddNewElements.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

C#: Edit Word Documents

Remove Paragraphs from a Word Document in C#

With the Spire.Doc library, you can perform a variety of document operations, including updating existing content, adding new elements, as well as removing elements from a Word document. For example, to remove a paragraph from the document, you can use the Section.Paragraphs.RemoveAt() method.

The following are the steps to remove paragraphs from a Word document using C#:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Remove a specific paragraph from the section using Section.Paragraphs.RemoveAt() method.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;

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

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get a specific section
            Section section = document.Sections[0];

            // Remove a specific paragraph
            section.Paragraphs.RemoveAt(0);

            // Save the document to a different Word file
            document.SaveToFile("RemoveParagraph.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

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.

Published in Document Operation
Tuesday, 31 May 2022 08:33

C#/VB.NET: Create a Word Document

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.

Published in Document Operation
Thursday, 09 December 2010 04:10

Solutions to Open Word in C#, VB.NET

No matter what users want to do on Word document, they should open it. This guide demonstrates several solutions to open Word in C# and VB.NET via Spire.Doc for .NET.

Open Existing Word

Spire.Doc for .NET provides a Document(String) constructor to enable users to initialize a new instance of Document class from the specified existing document.

[C#]
  Document document = new Document(@"E:\Work\Documents\Spire.Doc for .NET.docx");
[VB.NET]
Dim document As New Document("E:\Work\Documents\Spire.Doc for .NET.docx")

Spire.Doc for .NET also provides Document.LoadFromFile(String) method of Document class to open a Word document. The Word document can be .doc(Word 97-2003), .docx(Word 2007 and 2010) and .docm(Word with macro).

[C#]
  Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\Spire.Doc for .NET.docx");
[VB.NET]
 Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\Spire.Doc for .NET.docx")
          

Open Word in Read Mode

Spire.Doc for .NET provides Document.LoadFromFileInReadMode(String, FileFormat) method of Document class to load Word in Read-Only mode.

[C#]
            Document document = new Document();
            document.LoadFromFileInReadMode(@"E:\Work\Documents\Spire.Doc for .NET.docx",FileFormat.Docx);
[VB.NET]
            Dim document As New Document()
            document.LoadFromFileInReadMode("E:\Work\Documents\Spire.Doc for .NET.docx", FileFormat.Docx)

Load Word from Stream

Spire.Doc for .NET provides the constructor Document(Stream) to initialize a new instance of Document class from specified data stream and the method Document.LoadFromStream(Stream, FileFormat) to open document from Stream in XML or Microsoft Word document.

[C#]
            Stream stream = File.OpenRead(@"E:\Work\Documents\Spire.Doc for .NET.docx");
            Document document = new Document(stream);
OR
            Stream stream = File.OpenRead(@"E:\Work\Documents\Spire.Doc for .NET.docx"); 
            Document document = new Document();
            document.LoadFromStream(stream, FileFormat.Docx);
[VB.NET]
            Dim stream As Stream = File.OpenRead("E:\Work\Documents\Spire.Doc for .NET.docx")
            Dim document As New Document(stream)
OR
            Dim stream As Stream = File.OpenRead("E:\Work\Documents\Spire.Doc for .NET.docx")
            Dim document As New Document()
            document.LoadFromStream(stream, FileFormat.Docx)

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.

Published in Document Operation
Page 3 of 3