Thursday, 13 January 2011 08:33

Align Text in Word Document in C#, VB.NET

Word Text Alignment can be taken as one kind of text format tools. It allows users to align text with the following styles: Left, Right, Center and Justify. By default, text will be aligned right. Also, users can customize alignment. For example, the title is often aligned center and the body justified. Below demonstrate the effect by a screenshot.

Word Paragraph Alignment

Spire.Doc for .NET, a professional .NET word component to allow users to manipulate Word documents without automation. This guide will introduce the method to align text with C#, VB.NET via Spire.Doc for .NET. At first, there is a document with default alignment (Left) prepared. Then, four alignments will be applied for four paragraphs. Finally, set HorizontalAlignment property of Format under Paragraph class to realize alignment setting. Download and install Spire.Doc for .NET and use the following code

[C#]
using Spire.Doc;
using Spire.Doc.Documents;

namespace AlignText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load Document
            Document doc = new Document();
            doc.LoadFromFile(@"E:\Work\Documents\WordDocuments\Humor Them.docx");

            //Set Center Alignment
            Section s = doc.Sections[0];
            Paragraph p = s.Paragraphs[0];
            p.Format.HorizontalAlignment = HorizontalAlignment.Center;

            //Set Left Alignment
            Paragraph p1 = s.Paragraphs[1];
            p1.Format.HorizontalAlignment = HorizontalAlignment.Left;

            //Set Right Alignment
            Paragraph p2 = s.Paragraphs[2];
            p2.Format.HorizontalAlignment = HorizontalAlignment.Right;

            //Set Justify Alignment
            Paragraph p3 = s.Paragraphs[3];
            p3.Format.HorizontalAlignment = HorizontalAlignment.Justify;

            //Save and Launch
            doc.SaveToFile("WordAlignment.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("WordAlignment.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace AlignText
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim doc As New Document()
            doc.LoadFromFile("E:\Work\Documents\WordDocuments\Humor Them.docx")

            'Set Center Alignment
            Dim s As Section = doc.Sections(0)
            Dim p As Paragraph = s.Paragraphs(0)
            p.Format.HorizontalAlignment = HorizontalAlignment.Center

            'Set Left Alignment
            Dim p1 As Paragraph = s.Paragraphs(1)
            p1.Format.HorizontalAlignment = HorizontalAlignment.Left

            'Set Right Alignment
            Dim p2 As Paragraph = s.Paragraphs(2)
            p2.Format.HorizontalAlignment = HorizontalAlignment.Right

            'Set Justify Alignment
            Dim p3 As Paragraph = s.Paragraphs(3)
            p3.Format.HorizontalAlignment = HorizontalAlignment.Justify

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

Spire.Doc, an easy-to-use Word component, enables users to fast generate, open, save and modify Word document on .NET, WPF and Silverlight applications without Word automation and any other third party add-ins.

Published in Paragraph
Thursday, 13 January 2011 08:01

Set Word Font in C#, VB.NET

Word Font setting allows users to change text font style and size in a document. With wonderful font settings, the document layout and appearance will be more appealed. What’s more, in order to make some special words, phrases or paragraphs more obvious, users can set different font styles or size. For example, the title is often set as different font style with bigger size from body.

Spire.Doc for .NET, a professional .NET Word component, enables users to set font in Word document. This guide will shows how to set by using C#, VB.NET via Spire.Doc for .NET and the following screenshot presents result after setting.

Word Text Font Style

  • Load the document and get the paragraph which you want to set font.
  • Then, declare a new paragraph style and set FontName and FontSize properties of this style.
  • Finally, apply the style for paragraph and save document. Code as following:
[C#]
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordImage
{
    class ImageinWord
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\Humor Them.docx");

            //Get Paragraph
            Section s = document.Sections[0];
            Paragraph p = s.Paragraphs[1];

            //Set Font Style and Size
            ParagraphStyle style = new ParagraphStyle(document);
            style.Name = "FontStyle";
            style.CharacterFormat.FontName = "Century Gothic";
            style.CharacterFormat.FontSize = 20;
            document.Styles.Add(style);
            p.ApplyStyle(style.Name);

            //Save and Launch
            document.SaveToFile("font.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("font.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordImage
    Friend Class ImageinWord
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\WordDocuments\Humor Them.docx")

            'Get Paragraph
            Dim s As Section = document.Sections(0)
            Dim p As Paragraph = s.Paragraphs(1)

            'Set Font Style and Size
            Dim style As New ParagraphStyle(document)
            style.Name = "FontStyle"
            style.CharacterFormat.FontName = "Century Gothic"
            style.CharacterFormat.FontSize = 20
            document.Styles.Add(style)
            p.ApplyStyle(style.Name)

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

Spire.Doc, a professional Word component, can be used to generate, load, write, edit and save Word documents for .NET, Silverlight and WPF.

Published in Font
Thursday, 13 January 2011 07:48

How to Change Word Font Color in C#, VB.NET

Word Font Color is one kind of font formats to change text color in documents. By default, the color is black. However, the font color will be changed in order to make the special or important contents (for example, notices in instruction document) more obviously so that readers will pay more attention on the contents.

Spire.Doc for .NET, the professional .NET Word component, enables users to set font color by using C#, VB.NET. And this guide presents the method how to easily change font color in a Word document via Spire.Doc for .NET. The following screenshot is the result after changing.

Word Text Font Color

  • Load the document which you want to change font color at first.
  • Secondly, get paragraph 1(the title) in section 1.
  • Thirdly, declare a new ParagraphStyle. Give it a name. Set CharacterFormat property of ParagraphStyle. Then, apply this ParagraphStyle for paragraph 1.
  • Fourthly, set another ParagraphStyle for paragraph 2 as step 3.

Code as following:

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

namespace SetTextColor
{
    class TextColor
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\A GOOD MAN IS HARD TO FIND.docx");

            //Set Text Color for Paragraph 1(the Title)
            Section section = document.Sections[0];
            Paragraph p1 = section.Paragraphs[0];
            ParagraphStyle s1 = new ParagraphStyle(document);
            s1.Name = "TitleTextColor";
            s1.CharacterFormat.TextColor = Color.RosyBrown;
            document.Styles.Add(s1);
            p1.ApplyStyle(s1.Name);

            //Set Text Color for Paragraph 2
            Paragraph p2 = section.Paragraphs[1];
            ParagraphStyle s2 = new ParagraphStyle(document);
            s2.Name = "BodyTextColor";
            s2.CharacterFormat.TextColor = Color.DarkBlue;
            document.Styles.Add(s2);
            p2.ApplyStyle(s2.Name);
            
            //Save and Launch
            document.SaveToFile("TextColor.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("TextColor.docx");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace SetTextColor
    Friend Class TextColor
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\WordDocuments\A GOOD MAN IS HARD TO FIND.docx")

            'Set Text Color for Paragraph 1(the Title)
            Dim section As Section = document.Sections(0)
            Dim p1 As Paragraph = section.Paragraphs(0)
            Dim s1 As New ParagraphStyle(document)
            s1.Name = "TitleTextColor"
            s1.CharacterFormat.TextColor = Color.RosyBrown
            document.Styles.Add(s1)
            p1.ApplyStyle(s1.Name)

            'Set Text Color for Paragraph 2
            Dim p2 As Paragraph = section.Paragraphs(1)
            Dim s2 As New ParagraphStyle(document)
            s2.Name = "BodyTextColor"
            s2.CharacterFormat.TextColor = Color.DarkBlue
            document.Styles.Add(s2)
            p2.ApplyStyle(s2.Name)

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

Spire.Doc, a stand-alone Word component, enables developers/programmers to fast generate, load, write, modify and save Word documents on their .NET, WPF, Silverlight applications.

Published in Font

Word Replace function enables users to replace specified strings with new ones. All numbers of string will be detected and replaced at once time. Spire.Doc for .NET provides document.Replace method to realize replace function in C#, VB.NET. The following screenshot is the result after replacing.

Replace Word Text

By invoking document.Replace method, users can replace particular string with new value and set if the replacement is case-sensitive or the whole word will be affected. There are five possibilities document.Replace method provides.

  • Replace all entries of matchString(which will be replaced) regular expression with new value string.
  • Replace all entries of matchString regular expression with text range holder.
  • Replace specified matchString in matchDoc (specified document), taking into consideration of case-sensitive and whole word options.
  • Replace all entries of mathString with new value string, taking into consideration of case-sensitive and whole word options.
  • Replace all entries of matchString with text selection, taking into consideration of case-sensitive and whole word options.

This guide will introduce how to realize the fourth possibility above to replace the string "New Zealand" in the loaded document with "NZ". Download and install Spire.Doc for .NET. Follow the code:

[C#]
using Spire.Doc;

namespace ReplaceString
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\New Zealand.docx");

            document.Replace("New Zealand", "NZ", false, true);

            document.SaveToFile("Replace.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Replace.docx");
        }
    }
}
[VB]
Imports Spire.Doc

Namespace ReplaceString
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\WordDocuments\New Zealand.docx")

            document.Replace("New Zealand", "NZ", False, True)

            document.SaveToFile("Replace.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("Replace.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, a professional Word component, enables developers/programmers perform a wide range of processing tasks, such as generate, write, modify and save for their customize .NET, Silverlight and WPF applications.

Published in Text

Basic Knowledge about Office OpenXML

When talking about Office OpenXML, we may think of HTML. Actually, Office OpenXML is similar to HTML both are tag-based languages. The difference between Office OpenXML and HTML is that the tags which Office OpenXML uses are not predefined. If we want to create own tags within Office OpenXML, we need to follow a few rules.

Firstly, only one root element is contained in Office OpenXML document. The root element is often taken as document element and appears after the prolog section. Besides, all the Office OpenXML elements should contain end tags. Both start and end tag should be identical. Also, the elements can’t overlap. What’s more, all attribute values must use quotation marks and we can’t use some special characters within the text. After following the rules, the Office OpenXML document will be well formatted.

Use C# and VB.NET Convert Doc to Office OpenXML via Spire.Doc

Spire.Doc (Spire.Office) presents you an easy way to convert Doc to Office OpenXML. In this way, we can convert an exist Word doc file to Office OpenXML format with a few clicks. Now, just follow the simple steps.

Step 1: Create Project

Download Spire.Doc and install on system. Create a project through Visual Studio and add Spire.Doc DLL as reference.

Note: Please make sure Spire.Doc and Visual Studio are correctly installed on system

Step 2: Load Word Doc File

Load local Word doc file which we need to convert to Office OpenXML format. The following code can help us load it.

Document document = new Document();
document.LoadFromFile(@"D:\Sample.doc");

Step 3: Convert Doc to Office OpenXML

Spire.Doc supports convert Word Doc files to most of popular file formats such as PDF, HTML, Office OpenXML, EPub, RTF, Dot, Text, etc. Now, use the code below to convert Word to Office OpenXML.

document.SaveToFile("Sample.xml", FileFormat.Xml);

Step 4: Full Code

Now, write the full code into your project and press F5 to start the program.

[C#]
using System;
using System.Windows.Forms;
using Spire.Doc;
using Spire.Doc.Documents;

namespace to XML
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Create word document
            Document document = new Document();
            document.LoadFromFile(@"D:\Sample.doc");

            //Save doc file.
            document.SaveToFile("Sample.xml", FileFormat.Xml);

            //Launching the MS Word file.
            WordDocViewer("Sample.xml");
        }

        private void WordDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }

    }
}
[VB.NET]
Imports System
Imports System.Windows.Forms
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace to XML
	Partial Public Class Form1
		Inherits Form
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
			'Create word document
			Dim document As New Document()
			document.LoadFromFile("D:\Sample.doc")

			'Save doc file.
			document.SaveToFile("Sample.xml", FileFormat.Xml);

			'Launching the MS Word file.
			WordDocViewer("Sample.xml")
		End Sub

		Private Sub WordDocViewer(ByVal fileName As String)
			Try
				System.Diagnostics.Process.Start(fileName)
			Catch
			End Try
		End Sub

	End Class
End Namespace

After running the demo, you may find an Office OpenXML document launched on your browser:

Spire.Doc is an MS Word component which enables user to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document for .NET and Silverlight. Click to Learn more...

Published in Conversion
Friday, 07 January 2011 07:10

Insert Hyperlink to Word in C#, VB.NET

Word Hyperlink can be inserted automatically when users press ENTER or SPACEBAR after typing address of an existing Web page, such as www.e-iceblue.com. Also, users can insert customized hyperlink in Word for text to picture that they want to display as hyperlink. The hyperlink for text or picture can be Web page, E-mail address, other files or document.

Spire.Doc for .NET, a professional .NET Word component to manipulate Word documents, enables users to insert hyperlink in Word with C#/VB.NET. You can invoke the method paragraph.AppendHyperlink(string link, string text, HyperlinkType) to insert hyperlink in Word directly via Spire.Doc for .NET. And the HyperlinkType in method can be set as WebLink, EmailLink etc. Below is an effective screenshot after inserting hyperlink to Word in C#, VB.NET

Insert Word Hyperlink

Download and install Spire.Doc for .NET and then use the following code to insert hyperlink in Word.

[C#]
            //Create Word
            Document document = new Document();
            Section section = document.AddSection();
            Paragraph paragraph = section.AddParagraph();

            //Set Paragraph Styles
            ParagraphStyle txtStyle = new ParagraphStyle(document);
            txtStyle.Name = "Style";
            txtStyle.CharacterFormat.FontName = "Impact";
            txtStyle.CharacterFormat.FontSize = 16;
            txtStyle.CharacterFormat.TextColor = Color.RosyBrown;
            document.Styles.Add(txtStyle);

            ParagraphStyle hyperlinkstyle = new ParagraphStyle(document);
            hyperlinkstyle.Name = "linkStyle";
            hyperlinkstyle.CharacterFormat.FontName = "Calibri";
            hyperlinkstyle.CharacterFormat.FontSize = 15;
            document.Styles.Add(hyperlinkstyle);

            //Append Text and Set Text Format
            paragraph = section.AddParagraph();
            paragraph.AppendText("Home page");
            paragraph.ApplyStyle(txtStyle.Name);

            //Insert Hyperlink(Web Page)
            paragraph = section.AddParagraph();
            paragraph.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", HyperlinkType.WebLink);
            paragraph.ApplyStyle(hyperlinkstyle.Name);

            //Append text
            paragraph = section.AddParagraph();
            paragraph.AppendText("Contact US");
            paragraph.ApplyStyle(txtStyle.Name);

            //Insert Hyperlink(E-mail Address);
            paragraph = section.AddParagraph();
            paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "support@e-iceblue.com", HyperlinkType.EMailLink);
            paragraph.ApplyStyle(hyperlinkstyle.Name);

            //Save and Launch
            document.SaveToFile("Hyperlink.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Hyperlink.docx");
[VB.NET]
           'Create Word
            Dim document As New Document()
            Dim section As Section = document.AddSection()
            Dim paragraph As Paragraph = section.AddParagraph()

            'Set Paragraph Styles
            Dim txtStyle As New ParagraphStyle(document)
            txtStyle.Name = "Style"
            txtStyle.CharacterFormat.FontName = "Impact"
            txtStyle.CharacterFormat.FontSize = 16
            txtStyle.CharacterFormat.TextColor = Color.RosyBrown
            document.Styles.Add(txtStyle)

            Dim hyperlinkstyle As New ParagraphStyle(document)
            hyperlinkstyle.Name = "linkStyle"
            hyperlinkstyle.CharacterFormat.FontName = "Calibri"
            hyperlinkstyle.CharacterFormat.FontSize = 15
            document.Styles.Add(hyperlinkstyle)

            'Append Text and Set Text Format
            paragraph = section.AddParagraph()
            paragraph.AppendText("Home page")
            paragraph.ApplyStyle(txtStyle.Name)

            'Insert Hyperlink(Web Page)
            paragraph = section.AddParagraph()
            paragraph.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", HyperlinkType.WebLink)
            paragraph.ApplyStyle(hyperlinkstyle.Name)

            'Append text
            paragraph = section.AddParagraph()
            paragraph.AppendText("Contact US")
            paragraph.ApplyStyle(txtStyle.Name)

            'Insert Hyperlink(E-mail Address);
            paragraph = section.AddParagraph()
            paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "support@e-iceblue.com", HyperlinkType.EMailLink)
            paragraph.ApplyStyle(hyperlinkstyle.Name)

            'Save and Launch
            document.SaveToFile("Hyperlink.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("Hyperlink.docx")

Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.

Published in Hyperlink
Tuesday, 28 December 2010 07:50

Extract Images from Word in C#, VB.NET

Solution in this guide demonstrates how to extract images from an existing Word document and save them to a specified path in C# and VB.NET via Spire.Doc for .NET.

Image is one kind of document objects which belongs to paragraph items. Spire.Doc for .NET provides a DocumentObject class to store images in Document. And also provides a DocPicture class to get and set images of document. Download and Install Spire.Doc for .NET. Follow steps to extract images from Word.

  • Get each Paragraph of each Section in Document.
  • Get each DocumentObject of ChildObjects in Paragraph.
  • If the gotten DocumentObjectType is Picture, initialize a DocPicture class instance and assign the DocumentObject as value for this instance.
  • Initialize a String class instance to name extracted image instead of its original name by invoking String.Format(String format, object arg0)
  • Invoke DocPictrue.Image.Save(String, ImageFormat) method to save images.
[C#]
            //Load document
            Document document = new Document(@"E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx");
            int index = 0;

            //Get Each Section of Document
            foreach (Section section in document.Sections)
            {
                //Get Each Paragraph of Section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    //Get Each Document Object of Paragraph Items
                    foreach (DocumentObject docObject in paragraph.ChildObjects)
                    {
                        //If Type of Document Object is Picture, Extract.
                        if (docObject.DocumentObjectType == DocumentObjectType.Picture)
                        {
                            DocPicture picture = docObject as DocPicture;

                            //Name Image
                            String imageName = String.Format(@"images\Image-{0}.png", index);

                            //Save Image
                            picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
                            index++;
                        }
                    }
                }
            }
[VB.NET]
            'Load document
            Dim document As New Document("E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx")
            Dim index As Integer = 0

            'Get Each Section of Document
            For Each section As Section In document.Sections
                'Get Each Paragraph of Section
                For Each paragraph As Paragraph In section.Paragraphs
                    'Get Each Document Object of Paragraph Items
                    For Each docObject As DocumentObject In paragraph.ChildObjects
                        'If Type of Document Object is Picture, Extract.
                        If docObject.DocumentObjectType = DocumentObjectType.Picture Then
                            Dim picture As DocPicture = TryCast(docObject, DocPicture)

                            'Name Image
                            Dim imageName As String = String.Format("images\Image-{0}.png", index)

                            'Save Image
                            picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png)
                            index += 1
                        End If
                    Next docObject
                Next paragraph
            Next section

After debugging, all the extracted images are saved in a specified path. Open the directory, the images will be found.

Extract Word Image

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 Image and Shape
Tuesday, 28 December 2010 06:45

How to Traverse a Document Tree

Spire.Doc represents a document as a tree, every document element is a node of that tree. Some nodes such as section, paragraph and table may have many child nodes. For example, a section node has several paragraph nodes, a paragraph node has many text nodes and each row is the child node of a table node. And other nodes have no child node, such as text-range, image, form-field.
If a node has child nodes, it should be an instance of Spire.Doc.Interface.ICompositeObject.
If you want to operate all the nodes, you can use the tree navigation method to visit each node.

Document Tree Traversal

The following example demonstrates how to traverse a document tree to collect all nodes and ouput the text of all text-range nodes.
[C#]
using System;
using System.Collections.Generic;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Interface;
using Spire.Doc.Collections;

namespace ExtractText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Open a word document.
            Document document = new Document("Sample.doc");
            IList<IDocumentObject> nodes = GetAllObjects(document);
            foreach (IDocumentObject node in nodes)
            {
                //Judge the object type. 
                if (node.DocumentObjectType == DocumentObjectType.TextRange)
                {
                    TextRange textNode = node as TextRange;
                    Console.WriteLine(textNode.Text);
                }
            }
        }

        private static IList<IDocumentObject> GetAllObjects(Document document)
        {
        
            //Create a list.
            List<IDocumentObject> nodes = new List<IDocumentObject>();
            
            //Create a new queue.
            Queue<ICompositeObject> containers = new Queue<ICompositeObject>();
            
            //Put the document objects in the queue.
            containers.Enqueue(document);
            while (containers.Count > 0)
            {
                ICompositeObject container = containers.Dequeue();
                DocumentObjectCollection docObjects = container.ChildObjects;
                foreach (DocumentObject docObject in docObjects)
                { 
                    nodes.Add(docObject);
                    
                    //Judge the docObject.
                    if (docObject is ICompositeObject)
                    {
                        containers.Enqueue(docObject as ICompositeObject);
                    }
                }
            }

            return nodes;
        }
    }
}
          
[VB.NET]
Imports System
Imports System.Collections.Generic
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports Spire.Doc.Interface
Imports Spire.Doc.Collections

Module Module1

    Sub Main()
        'Open a word document.
        Dim document As New Document("Sample.doc")
        Dim nodes As IList(Of IDocumentObject)() = GetAllObjects(document)
        Dim containers As New Queue(Of ICompositeObject)()

        For Each node As IDocumentObject In nodes
        
            'Judge the object type.
            If (node.DocumentObjectType = DocumentObjectType.TextRange) Then
                Dim textNode As TextRange = node
                Console.WriteLine(textNode.Text)

            End If
        Next
    End Sub
    Function GetAllObjects(ByVal document As Document) As IList(Of IDocumentObject)
        
        'Create a list.
        Dim nodes As New List(Of IDocumentObject)()
        
        'Create a new queue.
        Dim containers As New Queue(Of ICompositeObject)()
        
        'Put the document objects in the queue.
        containers.Enqueue(document)
        While (containers.Count > 0)
            Dim container As ICompositeObject = containers.Dequeue()
            Dim docObjects As DocumentObjectCollection = container.ChildObjects
            For Each docObject As DocumentObject In docObjects
                nodes.Add(docObject)
                
                'Judge the docObject.
                If TypeOf docObject Is ICompositeObject Then
                    containers.Enqueue(TryCast(docObject, ICompositeObject))
                End If
            Next
        End While

        Return nodes
    End Function
End Module
          
Published in Others
Tuesday, 28 December 2010 02:25

Insert Word Bookmark in C#, VB.NET

Word bookmark is convenient for users to go to specified location and modify contents of bookmark range in a document. Solution in this guide introduces how to insert bookmark in existing Word document in C# and VB.NET via Spire.Doc for .NET. In this example, the bookmark range is from the end of the fourth paragraph to the end of the fifth paragraph. The following screenshot presents effect after Work bookmark inserting.

Insert Word Bookmark

Spire.Doc for .NET, a professional .NET Word component, provides two methods to insert Word bookmark, Paragraph.AppendBookmarkStart and Paragraph.AppendBookmarkEnd with parameter string name. The former method is used to append start of the bookmark with specified name into paragraph, while the later to append end of bookmark. Download and install Spire.Doc for .NET and follow the code to insert Word bookmark.

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

namespace WordBookmark
{
    class Bookmark
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Document\.NET Framework.docx");

            //Insert Bookmark
            Section section = document.Sections[0];
            section.Paragraphs[3].AppendBookmarkStart(".NETFramework");
            section.Paragraphs[4].AppendBookmarkEnd(".NETFramework");

            //Save and Launch 
            document.SaveToFile("Bookmark.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Bookmark.docx");
        }
    }
}
[VB.NET]
Imports System
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordBookmark
    Friend Class Bookmark
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Document\.NET Framework.docx")

            'Insert Bookmark
            Dim section As Section = document.Sections(0)
            section.Paragraphs(3).AppendBookmarkStart(".NETFramework")
            section.Paragraphs(4).AppendBookmarkEnd(".NETFramework")

            'Save and Launch 
            document.SaveToFile("Bookmark.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("Bookmark.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.

Published in Bookmark
Tuesday, 21 December 2010 16:34

Insert Header/Footer in Word Document in C#

Word header appears in the top of each page in a document, while Word footer appears in the bottom. Header and footer can be text or images, for example, document title, time and date, page numbers, company logo etc. Also, users can change or format header/footer contents according to own requirement.

Spire.Doc for .NET, a professional component to manipulate Word document with .NET, enables developers to insert header/footer in Word document by using C#/VB.NET. And this guide will show details about how to realize this function.

Users can set header or footer for Word document through HeadersFooters property of Section Class which Spire.Doc for .NET provides. Then, invoke header/footer.AddParagraph() method to add header/footer paragraph and add contents by invoking paragraph.AppendText(string) method. Now Download and Install Spire.Doc for .NET. Then, use the following code to insert header/footer in Word.

Insert Word Header

[C#]
           //Add Header
            Section section = document.Sections[0];
            HeaderFooter header = section.HeadersFooters.Header;
            Paragraph HParagraph = header.AddParagraph();
            TextRange HText = HParagraph.AppendText("Spire.Doc for .NET");

            //Set Header Text Format
            HText.CharacterFormat.FontName = "Algerian";
            HText.CharacterFormat.FontSize = 15;
            HText.CharacterFormat.TextColor = Color.RoyalBlue;

            //Set Header Paragraph Format
            HParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
            HParagraph.Format.Borders.Bottom.BorderType=BorderStyle.ThickThinMediumGap;
            HParagraph.Format.Borders.Bottom.Space = 0.05f;
            HParagraph.Format.Borders.Bottom.Color = Color.DarkGray;
[VB.NET]
             'Add Header
            Dim section As Section = document.Sections(0)
            Dim header As HeaderFooter = section.HeadersFooters.Header
            Dim HParagraph As Paragraph = header.AddParagraph()
            Dim HText As TextRange = HParagraph.AppendText("Spire.Doc for .NET")

            'Set Header Text Format
            HText.CharacterFormat.FontName = "Algerian"
            HText.CharacterFormat.FontSize = 15
            HText.CharacterFormat.TextColor = Color.RoyalBlue

            'Set Header Paragraph Format
            HParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left
            HParagraph.Format.Borders.Bottom.BorderType = BorderStyle.ThickThinMediumGap
            HParagraph.Format.Borders.Bottom.Space = 0.05F
            HParagraph.Format.Borders.Bottom.Color = Color.DarkGray

Header Result:

Insert Text Header/Footer

Insert Word Footer

[C#]
           //Add Footer
            HeaderFooter footer = section.HeadersFooters.Footer;
            Paragraph FParagraph = footer.AddParagraph();
            TextRange FText = FParagraph.AppendText("E-iceblue Co., Ltd. 2012 All Rights Reserverd");

            //Set Footer Text Format
            FText.CharacterFormat.FontName = "Calibri";
            FText.CharacterFormat.FontSize = 12;
            FText.CharacterFormat.TextColor = Color.DarkCyan;

            //Set Footer Paragrah Format
            FParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
            FParagraph.Format.Borders.Top.BorderType=BorderStyle.ThinThinSmallGap;
            FParagraph.Format.Borders.Top.Space = 0.15f;
            FParagraph.Format.Borders.Color = Color.DarkGray;
[VB.NET]
           'Add Footer
            Dim footer As HeaderFooter = section.HeadersFooters.Footer
            Dim FParagraph As Paragraph = footer.AddParagraph()
            Dim FText As TextRange = FParagraph.AppendText("E-iceblue Co., Ltd. 2012 All Rights Reserverd")

            'Set Footer Text Format
            FText.CharacterFormat.FontName = "Calibri"
            FText.CharacterFormat.FontSize = 12
            FText.CharacterFormat.TextColor = Color.DarkCyan

            'Set Footer Paragrah Format
            FParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right
            FParagraph.Format.Borders.Top.BorderType = BorderStyle.ThinThinSmallGap
            FParagraph.Format.Borders.Top.Space = 0.15F
            FParagraph.Format.Borders.Color = Color.DarkGray

Footer Result:

Insert Text Header/Footer

Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.

Published in Header and Footer
Page 2 of 4