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.
No comments:
Post a Comment