Tuesday, May 6, 2014

C# word operate conclusion Spire.doc

For the recent project requirements, we need to do some processing on the word document. We did a lot of search online, and found that most of them are incomplete and repeated. Few of complete guides for word component are not free. Finally I am lucky to find a free C# word library to meet all my requirements. In order to prepare others to use it later, I make a conclusion as below. Wish it helps.

How to get it?
This free word component is listed on the Codeplex, you can get the msi file directly from there. It also offers some source code.

Operate word document conclusion.

1.       Open an existing word document. This is the basic and must step to process the word document. And it offers 3 different ways.
Solution1: Initialize a new instance of Document class from the specified existing document.
Document document = new Document(@"..\..\Sample.docx");

Solution2: Load a word document from the file.
Document document = new Document();
document.LoadFromFile(@"..\..\Sample.docx");
       
Solution3: Load word document from Stream
Stream stream = File.OpenRead(@"..\..\Sample.docx");
Document document = new Document(stream);

2. How to create Table:
Document document = new Document();
Section section = document.AddSection();

Table table = section.AddTable(true);
table.ResetCells(2, 3);

TableRow row = table.Rows[0];
row.IsHeader = true;

Paragraph para = row.Cells[0].AddParagraph();
TextRange TR = para.AppendText("Item");

para = row.Cells[1].AddParagraph();
TR = para.AppendText("Description");

para = row.Cells[2].AddParagraph();
TR = para.AppendText("Qty");

document.SaveToFile("WordTable.docx");

System.Diagnostics.Process.Start("WordTable.docx");








We can also set the rows and cells board and height.

3. How to insert hyperlinks. You can insert two types of hyperlinks, Email link and webmail link.
Document document = new Document();
Section section = document.AddSection();

//Insert URL hyperlink
Paragraph paragraph = section.AddParagraph();
paragraph.AppendText("Home page");
paragraph.ApplyStyle(BuiltinStyle.Heading2);
paragraph = section.AddParagraph();
paragraph.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", HyperlinkType.WebLink);

//Insert email address hyperlink
paragraph = section.AddParagraph();
paragraph.AppendText("Contact US");
paragraph.ApplyStyle(BuiltinStyle.Heading2);
paragraph = section.AddParagraph();
paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "support@e-iceblue.com", HyperlinkType.EMailLink);

document.SaveToFile("Hyperlink.docx");
System.Diagnostics.Process.Start("Hyperlink.docx");

4. How to add comments.

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

Paragraph paragraph = section.AddParagraph();
paragraph.AppendText("Home Page of ");
TextRange textRange = paragraph.AppendText("e-iceblue");

Comment comment1 = paragraph.AppendComment("www.e-iceblue.com");
comment1.AddItem(textRange);
comment1.Format.Author = "Harry Hu";
comment1.Format.Initial = "HH";

document.SaveToFile("Comment.docx");
System.Diagnostics.Process.Start("Comment.docx");



5. How to add bookmarks:

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

Paragraph paragraph = section.AddParagraph();

paragraph.AppendBookmarkStart("SimpleBookMark");
paragraph.AppendText("This is a simple book mark.");
paragraph.AppendBookmarkEnd("SimpleBookMark");

document.SaveToFile("Bookmark.docx");
System.Diagnostics.Process.Start("Bookmark.docx");

6. MailMerge

Document document = new Document();
document.LoadFromFile("Fax.doc");

string[] filedNames = new string[] { "Contact Name", "Fax", "Date" };

string[] filedValues = new string[] { "John Smith", "+1 (69) 123456", System.DateTime.Now.Date.ToString() };

document.MailMerge.Execute(filedNames, filedValues);

document.SaveToFile("MailMerge.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("MailMerge.doc");

7. FormField. This part contains create and fill formfield.
Create FormField:
//Add new section to document
Section section = document.AddSection();

//Add Form to section
private void AddForm(Section section)

//add text input field
TextFormField field
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput) as TextFormField;

//add dropdown field
DropDownFormField list
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown) as DropDownFormField;

//add checkbox field
fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox);


Fill FormField:
//Fill data from XML file
using (Stream stream = File.OpenRead(@"..\..\..\Data\User.xml"))
{
    XPathDocument xpathDoc = new XPathDocument(stream);
XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");

Fill data:

foreach (FormField field in document.Sections[0].Body.FormFields)
  {
     String path = String.Format("{0}/text()", field.Name);
     XPathNavigator propertyNode = user.SelectSingleNode(path);
     if (propertyNode != null)
     {
         switch (field.Type)
         {
             case FieldType.FieldFormTextInput:
                  field.Text = propertyNode.Value;
                  break;

             case FieldType.FieldFormDropDown:
                  DropDownFormField combox = field as DropDownFormField;
                  for(int i = 0; i < combox.DropDownItems.Count; i++)
                  {
                      if (combox.DropDownItems[i].Text == propertyNode.Value)
                      {
                         combox.DropDownSelectedIndex = i;
                         break;
                      }
                      if (field.Name == "country" && combox.DropDownItems[i].Text == "Others")
                      {
                         combox.DropDownSelectedIndex = i;
                      }
                  }
                  break;

             case FieldType.FieldFormCheckBox:
                  if (Convert.ToBoolean(propertyNode.Value))
                  {
                      CheckBoxFormField checkBox = field as CheckBoxFormField;
                      checkBox.Checked = true;
                  }
                  break;
            }
       }
   }
 }

8. Merge word document.
//Load two documents
//Load Document1 and Document2
Document DocOne = new Document();
DocOne.LoadFromFile(@"E:\Work\Document\welcome.docx", FileFormat.Docx);
Document DocTwo = new Document();
DocTwo.LoadFromFile(@"E:\Work\Document\New Zealand.docx", FileFormat.Docx);

//Merge
foreach (Section sec in DocTwo.Sections)
{
 DocOne.Sections.Add(sec.Clone());
}
//Save and Launch
DocOne.SaveToFile("Merge.docx", FileFormat.Docx);

9. Protect document. You can set password or add watermarks to the word document to protect the document. Both text and image watermarks supported.

//Protect with password
document.Encrypt("eiceblue");

//Add Text watermark:
TextWatermark txtWatermark = new TextWatermark();
txtWatermark.Text = "Microsoft";
txtWatermark.FontSize = 90;
txtWatermark.Layout = WatermarkLayout.Diagonal;
document.Watermark = txtWatermark;

//Add Image watermark:
PictureWatermark picture = new PictureWatermark();
picture.Picture = System.Drawing.Image.FromFile(@"..\imagess.jpeg");
picture.Scaling = 250;
document.Watermark = picture;

10. Conversion function is the most popular requirements for processing word documents. With the help of free Spire.Doc for .net, conversion becomes very simple and easy. Only three same lines code is involved and you can convert word document to often used formats, such as PDF, HTML and Image.

Convert word document to PDF

document.SaveToFile("Target PDF.PDF", FileFormat.PDF);

Convert word document to Image

Image image = document.SaveToImages(0, ImageType.Bitmap);
image.Save("Sample.tiff", ImageFormat.Tiff);

Convert word document to HTML:

document.SaveToFile("Target HTML.html", FileFormat.Html);
WordDocViewer(""Target HTML.html");

Conclusion: This is a powerful and free C# word component without Word automation and any other third party add-ins.



Monday, May 5, 2014

Mail Merge using Spire.doc

Let us think about this scenario: You are employed by an IT company. One of your company’s products has been updated in a major scale. You need to inform all the customers of that product. And it is a quiet long list. It is very silly to write the notice one by one. It costs much time and man-power. You need a better solution to fulfill the work quickly and more efficiently. Here I provide you a solution to do the work by using a component.  You can check the component here (https://freeword.codeplex.com/).

It is a notice and the context is the same. First we create a template. This template is used to create all the notices. Check the template below.
Then what need to be done is to replace the text in brackets to the information of users. Here is code to do the work:
               private int lastIndex = 0;

        private void button1_Click(object sender, EventArgs e)
        {
            //create word document
            Document document = new Document();
            document.LoadFromFile("template.doc");
            lastIndex = 0;

            //informaton of customers
            List<CustomerRecord> customerRecords = new List<CustomerRecord>();
            CustomerRecord c1 = new CustomerRecord();
            c1.ContactName = "Lucy";
            c1.Fax = "786-324-10";
            c1.Date = DateTime.Now;
            customerRecords.Add(c1);

            CustomerRecord c2 = new CustomerRecord();
            c2.ContactName = "Lily";
            c2.Fax = "779-138-13";
            c2.Date = DateTime.Now;
            customerRecords.Add(c2);

            CustomerRecord c3 = new CustomerRecord();
            c3.ContactName = "James";
            c3.Fax = "363-287-02";
            c3.Date = DateTime.Now;
            customerRecords.Add(c3);

            //execute mailmerge
            document.MailMerge.MergeField += new MergeFieldEventHandler(MailMerge_MergeField);
            document.MailMerge.ExecuteGroup(new MailMergeDataTable("Customer", customerRecords));

            //save doc file.
            document.SaveToFile("result.doc", FileFormat.Doc);

            //viewer the result file.
            System.Diagnostics.Process.Start("result.doc");
        }

        void MailMerge_MergeField(object sender, MergeFieldEventArgs args)
        {
            //next row
            if (args.RowIndex > lastIndex)
            {
                lastIndex = args.RowIndex;
                AddPageBreakForMergeField(args.CurrentMergeField);
            }
        }

        void AddPageBreakForMergeField(IMergeField mergeField)
        {
            //find position of needing to add page break
            bool foundGroupStart = false;
            Paragraph paramgraph = mergeField.PreviousSibling.Owner as Paragraph;
            MergeField merageField = null;
            while (!foundGroupStart)
            {
                paramgraph = paramgraph.PreviousSibling as Paragraph;
                for (int i = 0; i < paramgraph.Items.Count; i++)
                {
                    merageField = paramgraph.Items[i] as MergeField;
                    if ((merageField != null) && (merageField.Prefix == "GroupStart"))
                    {
                        foundGroupStart = true;
                        break;
                    }
                }
            }

            paramgraph.AppendBreak(BreakType.PageBreak);
        }


    //class to represent customers
    public class CustomerRecord
    {
        private string m_contactName;
        public string ContactName
        {
            get
            {
                return m_contactName;
            }
            set
            {
                m_contactName = value;
            }
        }

        private string m_fax;
        public string Fax
        {
            get
            {
                return m_fax;
            }
            set
            {
                m_fax = value;
            }
        }

        private DateTime m_date;
        public DateTime Date
        {
            get
            {
                return m_date;
            }
            set
            {
                m_date = value;
            }
        }
    }
Screenshots of the result file: