Document Operation

Document Operation (21)

Starts from version 7.6.5, Spire.Doc supports to add Latex math code to Word document in C#. This article will show you how to add Latex Math Symbols and equation to word document.

//create a word document
Document doc = new Document();

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

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

//add a LatexMathcode to the first paragraph
OfficeMath officeMath = new OfficeMath(doc);
paragraph.Items.Add(officeMath);
officeMath.FromLatexMathCode("x^{2}+\\sqrt{x^{2}+1}=2");

//add equation to the second paragraph
Paragraph paragraph2 = section.AddParagraph();
OfficeMath officeMath1 = new OfficeMath(doc);
paragraph2.Items.Add(officeMath1);
officeMath1.FromLatexMathCode("\\forall x \\in X, \\quad \\exists y \\leq \\epsilon");

//add symbols to the third paragraph
Paragraph paragraph3 = section.AddParagraph();
OfficeMath officeMath2 = new OfficeMath(doc);
paragraph3.Items.Add(officeMath2);
officeMath2.FromLatexMathCode(" \\alpha,\\beta, \\gamma, \\Gamma, \\pi, \\Pi, \\phi, \\varphi, \\mu, \\Phi");

//save the document to file       
doc.SaveToFile("Equation.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("Equation.docx");

Effective screenshot after adding latex math code and symbols to the word document:

C# insert math equation and symbol to Word document

Besides the Combo Box, Text, Date Picker and Drop-Down List content controls, Checkbox and picture content control also are the mostly used content control in word document. Spire.Doc supports to add many kinds of content controls to the word document. This article will show you how to add checkbox and picture content control to word document by Spire.Doc for .NET.

Code snippets of how to add checkbox and picture content control:

static void Main(string[] args)
{
    //Create a new word document
    Document document = new Document();

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

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

    //Add checkbox content control
    StructureDocumentTagInline sdt = new StructureDocumentTagInline(document);
    paragraph = section.AddParagraph();
    sdt = new StructureDocumentTagInline(document);
    sdt.CharacterFormat.FontSize = 20;
    paragraph.ChildObjects.Add(sdt);
    sdt.SDTProperties.SDTType = SdtType.CheckBox;
    SdtCheckBox scb = new SdtCheckBox();
    sdt.SDTProperties.ControlProperties = scb;
    TextRange tr = new TextRange(document);
    tr.CharacterFormat.FontName = "MS Gothic";
    tr.CharacterFormat.FontSize = 20;
    sdt.ChildObjects.Add(tr);
    scb.Checked = true;

    sdt.SDTProperties.Alias = "CheckoBox";
    sdt.SDTProperties.Tag = "Checkbox";

    //Add picture content control
    paragraph = section.AddParagraph();
    sdt = new StructureDocumentTagInline(document);
    paragraph.ChildObjects.Add(sdt);
    sdt.SDTProperties.ControlProperties = new SdtPicture();

    sdt.SDTProperties.Alias = "Picture";
    sdt.SDTProperties.Tag = "Picture";

    DocPicture pic = new DocPicture(document) { Width = 10, Height = 10 };
    pic.LoadImage(Image.FromFile("Logo.jpg"));
    sdt.SDTContent.ChildObjects.Add(pic);

    document.SaveToFile("Sample.docx", FileFormat.Docx2013);
}

Effective screenshot after adding checkbox and picture content control to word document:

Add checkbox and picture content control to word document in C#

With Spire.Doc, developers can quickly detect if a Word document contains VBA macros and remove all of the VBA macros from a word document. This article is going to show you the detail steps of how to detect and remove VBA macros from word document using Spire.Doc.

Detail steps:

Step 1: Initialize a Document object and load the Word document.

Document document = new Document();
document.LoadFromFile("Input.docm");

Step 2: If the document contains Macros, remove them from the document.

if (document.IsContainMacro)
{
    document.ClearMacros();
}

Step 3: Save the document.

document.SaveToFile("Output.docm", FileFormat.Docm);

Full code:

using Spire.Doc;

namespace Remove_Macros_from_Word
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize a Document object
            Document document = new Document();
            //Load the Word document
            document.LoadFromFile("Input.docm");

            //If the document contains macros, remove them from the document
            if (document.IsContainMacro)
            {
                document.ClearMacros();
            }
            
            //Save the document
            document.SaveToFile("Output.docm", FileFormat.Docm);            
        }
    }
}
Thursday, 08 March 2018 03:46

How to clone a word document in C#

Written by support iceblue

With Spire.Doc, we can copy the content from one word document to another word document in C#. When we need to generate a large amount of documents from a single document, clone the document will be much easier. The clone method speeds up the generation of the word documents and developers only need one single line of code to get the copy of the word document.

Now we will show the code snippet of how to clone a word document in C#.

Step 1: Create a new instance of Document and load the document from file.

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

Step 2: Clone the word document.

doc.Clone();

Step 3: Save the document to file.

doc.SaveToFile("Cloneword.docx", FileFormat.Docx2010);

Effective screenshot of clone the word document:

How to clone a word document in C#

Full codes of clone a word document:

static void Main(string[] args)
{
               
    Document doc = new Document();
    doc.LoadFromFile("Sample.docx",FileFormat.Docx2010);

    doc.Clone();

    doc.SaveToFile("Cloneword.docx", FileFormat.Docx2010);

   
}

Document variables are used to preserve macro settings in between macro sessions. Spire.Doc allows adding variables, counting the number of variables, retrieving the name and value of variables, and removing specific variables in a Word document.

Add a Variable

Use the Add method to add a variable to a document. The following example adds a document variable named "A1" with a value of 12 to the document.

//Instantiate a document object
Document document = new Document();
//Add a section
Section section = document.AddSection();
//Add a paragraph
Paragraph paragraph = section.AddParagraph();
//Add a DocVariable Filed
paragraph.AppendField("A1", FieldType.FieldDocVariable);
//Add a document variable to the DocVariable Filed
document.Variables.Add("A1", "12");
 //Update fields
document.IsUpdateFields = true;
//Save and close the document object
document.SaveToFile("AddVariable.docx", FileFormat.Docx2013);
document.Close();

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Count the number of Variables

Use the Count property to return the number of variables in a document.

//Load the document
Document document = new Document("AddVariable.docx");
//Get the number of variables in the document
int number = document.Variables.Count;

Console.WriteLine(number);

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Retrieve Name and Value of a Variable

Use the GetNameByIndex and GetValueByIndex methods to retrieve the name and value of the variable by index, and the Variables[String Name] to retrieve or set the value of the variable by name.

//Load the document
Document document = new Document("AddVariable.docx");

// Retrieve name of the variable by index
string s1 = document.Variables.GetNameByIndex(0);

// Retrieve value of the variable by index
string s2 = document.Variables.GetValueByIndex(0);

// Retrieve or set value of the variable by name
string s3 = document.Variables["A1"];

Console.WriteLine("{0} {1} {2}", s1, s2, s3);

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Remove a specific Variable

Use the Remove method to remove the variable from the document.

//Load the document
Document document = new Document("AddVariable.docx");

//Remove the variable by name
document.Variables.Remove("A1");

//Save and close the document object
document.SaveToFile("RemoveVariable.docx", FileFormat.Docx2013);
document.Close();

The track changes has been used to keep track of the every changes that made to the Word document. It helps to record every edit, insertion, deletion, or modification in a word document. We have demonstrated how to accept/reject the tracked changes on word document in C#. This article will show you how to enable track changes of the document.

Step 1: Create a new word document and load the document from file.

Document document = new Document();
document.LoadFromFile("Sample.docx", FileFormat.Docx2010);

Step 2: Enable the track changes.

document.TrackChanges = true;

Step 3: Save the document to file.

document.SaveToFile("Enable Trackchanges.docx", FileFormat.Docx2010);

Effective screenshot:

How to enable track changes of the word document

Full codes:

Document document = new Document();
document.LoadFromFile("Sample.docx", FileFormat.Docx2010);

document.TrackChanges = true;
                        
document.SaveToFile("Enable Trackchanges.docx", FileFormat.Docx2010);

When we operate the word documents by edit the wording, and its format on the word documents, we usually use Microsoft Word's Tracking Changes feature to mark our every changes. Later if we want to share the final version of our document to others, we need to remove the tracked changes by accepting them or rejecting them. Spire.Doc offers a property Document.TrackChanges to turn on/off track changes and the method of Document.AcceptChanges();/Document.RejectChanges(); to accept/reject the track changes. This article will show you how to accept/reject the tracked changes on word document in C# with the help of Spire.Doc.

Firstly view the sample word document with tracked changes:

How to accept/reject the tracked changes on word document in C#

Here comes to the steps of how to accept or reject the tracked changes:

Step 1: Create a new word document and load the document from file.

Document doc = new Document();
doc.LoadFromFile("sample.docx");

Step 2: Get the first section and the paragraph we want to accept/reject the changes.

Section sec = doc.Sections[0];
Paragraph para = sec.Paragraphs[0];

Step 3: Accept the changes or reject the changes.

para.Document.AcceptChanges();
//para.Document.RejectChanges();

Step 4: Save the document to file.

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

Effective screenshot after accept the tracked changes:

How to accept/reject the tracked changes on word document in C#

Full codes:

static void Main(string[] args)
{
    Document doc = new Document();
    doc.LoadFromFile("sample.docx");

    Section sec = doc.Sections[0];
    Paragraph para = sec.Paragraphs[0];

    para.Document.AcceptChanges();

//para.Document.RejectChanges();

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

}

With the help of Spire.Doc for .NET, not only can we split a word document by section, but also can split it by page break. We've already introduced how to split a Word document into multiple documents by section break. In this article, we'll learn how to split a word document by page break with Spire.Doc for .NET.

Please view the following screenshot of the original word document which has two page breaks at the end of the first and the second page.

How to split a word document by page break in C#

Now refer to the following detail steps to split it into 3 separate documents by page breaks.

Step 1: Create a word document and load the original word document.

Document original = new Document();
original.LoadFromFile("New Zealand.docx");

Step 2: Create a new word document and add a section to it.

Document newWord = new Document();
Section section = newWord.AddSection();

Step 3: Split the original word document into separate documents according to page break.

int index = 0;
//traverse through all sections of original document
foreach (Section sec in original.Sections)
{
    //traverse through all body child objects of each section
    foreach (DocumentObject obj in sec.Body.ChildObjects)
    {
        if (obj is Paragraph)
        {
            Paragraph para = obj as Paragraph;
            //add paragraph object in original section into section of new document
            section.Body.ChildObjects.Add(para.Clone());
            foreach (DocumentObject parobj in para.ChildObjects)
            {
                if (parobj is Break && (parobj as Break).BreakType == BreakType.PageBreak)
                {
                    //get the index of page break in paragraph
                    int i = para.ChildObjects.IndexOf(parobj);
                    //remove the page break from its paragraph
                    section.Body.LastParagraph.ChildObjects.RemoveAt(i);

                    //save the new document to a .docx file.
                    newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);
                    index++;

                    //create a new document
                    newWord = new Document();
                    //add a section for document
                    section = newWord.AddSection();
                    //add paragraph object in original section into section of new document
                    section.Body.ChildObjects.Add(para.Clone());
                    if (section.Paragraphs[0].ChildObjects.Count == 0)
                    {
                        //remove the first blank paragraph
                        section.Body.ChildObjects.RemoveAt(0);
                    }
                    else
                    {
                        //remove the child objects before the page break
                        while (i >= 0)
                        {
                            section.Paragraphs[0].ChildObjects.RemoveAt(i);
                            i--;
                        }
                    }
                }
            }
        }
        if (obj is Table)
        {
            //add table object in original section into section of new document
            section.Body.ChildObjects.Add(obj.Clone());
        }
    }
}
//save to a .docx file
newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);

Output:

How to split a word document by page break in C#

Full codes:

using System;
using Spire.Doc;
using Spire.Doc.Documents;

namespace Split_Word_Document_by_Page_Break
{
    class Program
    {
        static void Main(string[] args)
        {
            Document original = new Document();
            original.LoadFromFile("New Zealand.docx");
            Document newWord = new Document();
            Section section = newWord.AddSection();

            int index = 0;
            foreach (Section sec in original.Sections)
            {
                foreach (DocumentObject obj in sec.Body.ChildObjects)
                {
                    if (obj is Paragraph)
                    {
                        Paragraph para = obj as Paragraph;
                        section.Body.ChildObjects.Add(para.Clone());

                        foreach (DocumentObject parobj in para.ChildObjects)
                        {
                            if (parobj is Break && (parobj as Break).BreakType == BreakType.PageBreak)
                            {
                                int i = para.ChildObjects.IndexOf(parobj);
                                section.Body.LastParagraph.ChildObjects.RemoveAt(i);
                                newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);
                                index++;

                                newWord = new Document();
                                section = newWord.AddSection();
                                section.Body.ChildObjects.Add(para.Clone());
                                if (section.Paragraphs[0].ChildObjects.Count == 0)
                                {
                                    section.Body.ChildObjects.RemoveAt(0);
                                }
                                else
                                {
                                    while (i >= 0)
                                    {
                                        section.Paragraphs[0].ChildObjects.RemoveAt(i);
                                        i--;
                                    }
                                }
                            }
                        }
                    }
                    if (obj is Table)
                    {
                        section.Body.ChildObjects.Add(obj.Clone());
                    }
                }
            }
            newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);
        }
    }
}

In Word, we can split a word document in an easiest way - open a copy of the original document, delete the sections that we don’t want and then save the remains to local drive. But doing this section by section is rather cumbersome and boring. This article will explain how we can use Spire.Doc for .NET to programmatically split a Word document into multiple documents by section break instead of copying and deleting manually.

Detail steps and code snippets:

Step 1: Initialize a new word document object and load the original word document which has two sections.

Document document = new Document();
document.LoadFromFile("Test.docx");

Step 2: Define another new word document object.

Document newWord;

Step 3: Traverse through all sections of the original word document, clone each section and add it to a new word document as new section, then save the document to specific path.

for (int i = 0; i < document.Sections.Count; i++)
{
    newWord = new Document();
    newWord.Sections.Add(document.Sections[i].Clone());
    newWord.SaveToFile(String.Format(@"test\out_{0}.docx", i));
}

Run the project and we'll get the following output:

How to split a Word document into multiple documents by section break in C#

Full codes:

using System;
using Spire.Doc;

namespace Split_Word_Document
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("Test.doc");
            Document newWord;
            for (int i = 0; i < document.Sections.Count; i++)
            {
                newWord = new Document();
                newWord.Sections.Add(document.Sections[i].Clone());
                newWord.SaveToFile(String.Format(@"test\out_{0}.docx", i));
            }
        }
    }
}

Content controls are Microsoft Word entities that act as containers for specific content such as dates, lists, or paragraphs of formatted text. With the help of content controls, we can easily create structured templates, forms or documents by specifying the kind of content (for example, a date, or text), restricting or allowing editing of the content etc. in a word document.

In this article, we will introduce how to add Combo Box, Text, Date Picker and Drop-Down List content controls to a word document in C# using Spire.Doc for .NET.

Here we only explained how to add a Combo Box content control to a word document in detailed steps, full codes are demonstrated at the end of this article.

Add Combo Box content control

Detail steps and code snippets:

Step 1: Create a new word document, add a section to the document and a paragraph to the section.

Document document = new Document();
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();

Step 2: Use the StructureDocumentTagInline class to create a content control, call Paragraph.ChildObjects.Add () method to add the content control to the paragraph and specify its SDT type to Combo box.

StructureDocumentTagInline sd = new StructureDocumentTagInline(document);
paragraph.ChildObjects.Add(sd);
sd.SDTProperties.SDTType = SdtType.ComboBox;

Step 3: Use the SdtComboBox class to create a combo box, add the items that are used for selecting to the combo box, assign the combo box to the content control, then set the display text.

SdtComboBox cb = new SdtComboBox();
cb.ListItems.Add(new SdtListItem("Cat"));
cb.ListItems.Add(new SdtListItem("Dog"));
sd.SDTProperties.ControlProperties = cb;
TextRange rt = new TextRange(document);
rt.Text = cb.ListItems[0].DisplayText;
sd.SDTContent.ChildObjects.Add(rt);

Step 4: Save and launch the file.

string resultfile = "sample.docx";
document.SaveToFile(resultfile, FileFormat.Docx);
System.Diagnostics.Process.Start(resultfile);

Below is the result word document after adding a Combo Box Content Control:

How to Add Content Controls to Word documents in C#

Full codes:

using System;
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace Add_content_controls_to_word_documents
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creat a new word document
            Document document = new Document();
            Section section = document.AddSection();
            Paragraph paragraph = section.AddParagraph();

            //Add Combo Box Content Control
            StructureDocumentTagInline sd = new StructureDocumentTagInline(document);
            paragraph.ChildObjects.Add(sd);
            sd.SDTProperties.SDTType = SdtType.ComboBox;
            SdtComboBox cb = new SdtComboBox();
            cb.ListItems.Add(new SdtListItem("Cat"));
            cb.ListItems.Add(new SdtListItem("Dog"));
            sd.SDTProperties.ControlProperties = cb;
            TextRange rt = new TextRange(document);
            rt.Text = cb.ListItems[0].DisplayText;
            sd.SDTContent.ChildObjects.Add(rt);

            //Add Text Content Control
            paragraph = section.AddParagraph();
            sd = new StructureDocumentTagInline(document);
            paragraph.ChildObjects.Add(sd);
            sd.SDTProperties.SDTType = SdtType.Text;
            SdtText text = new SdtText(true);
            text.IsMultiline = true;
            sd.SDTProperties.ControlProperties = text;
            rt = new TextRange(document);
            rt.Text = "Text";
            sd.SDTContent.ChildObjects.Add(rt);

            //Add Date Picker Content Control
            paragraph = section.AddParagraph();
            sd = new StructureDocumentTagInline(document);
            paragraph.ChildObjects.Add(sd);
            sd.SDTProperties.SDTType = SdtType.DatePicker;
            SdtDate date = new SdtDate();
            date.CalendarType = CalendarType.Default;
            date.DateFormat = "yyyy.MM.dd";
            date.FullDate = DateTime.Now;
            sd.SDTProperties.ControlProperties = date;
            rt = new TextRange(document);
            rt.Text = "1990.02.08";
            sd.SDTContent.ChildObjects.Add(rt);

            //Add Drop-Down List Content Control
            paragraph = section.AddParagraph();
            sd = new StructureDocumentTagInline(document);
            paragraph.ChildObjects.Add(sd);
            sd.SDTProperties.SDTType = SdtType.DropDownList;
            SdtDropDownList sddl = new SdtDropDownList();
            sddl.ListItems.Add(new SdtListItem("Harry"));
            sddl.ListItems.Add(new SdtListItem("Jerry"));
            sd.SDTProperties.ControlProperties = sddl;
            rt = new TextRange(document);
            rt.Text = sddl.ListItems[0].DisplayText;
            sd.SDTContent.ChildObjects.Add(rt);

            //Save and launch the file
            string resultfile = "sample.docx";
            document.SaveToFile(resultfile, FileFormat.Docx);
            System.Diagnostics.Process.Start(resultfile);
            
        }
    }
}
Page 1 of 2