Feb 12, 2010

Insert and formatting a picture into a word document using c#

Word Automation through C# is all about programmatically generating the Word Document using C# code. Working on Word is considered to be straightforward, but doing the same programmatically gets a little intricate. Word automation almost completely involves working with objects and reference types. Almost all of the tasks which we perform on word 2003 can be done programmatically using C#. Tasks like Inserting Table of Contents, inserting pictures, formatting etc can all be done programmatically.

In this example, I have a ms word 2007 document template having a 2*2 table.Here are the lines of code to insert a picture into table cell and set its height and width

using Microsoft.Office.Interop.Word;

object nullObj = System.Reflection.Missing.Value;

ApplicationClass objWord = new ApplicationClass();

Document objWordDoc = objWord.Documents.Open(ref fileName, ref nullObj, ref nullObj, ref nullObj, ref nullObj, ref nullObj, ref nullObj, ref nullObj, ref nullObj, ref nullObj, ref nullObj, ref isVisible, ref nullObj, ref nullObj, ref nullObj, ref nullObj);

objWordDoc.Activate();

Microsoft.Office.Interop.Word.Table table = objWordDoc.Tables[1]; Object objNull = Type.Missing;

for (int i = 0; i <>

{

table.Rows.Add(ref objNull);

table.Rows.Add(ref objNull);

table.Cell(tableRow, 1).Range.Text = dsComments.Tables[0].Rows[i]["RowId"].ToString();

table.Cell(tableRow, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

table.Cell(tableRow, 1).Range.Bold = 0;

table.Cell(tableRow + 1, 1).Range.Text = dsComments.Tables[0].Rows[i]["Comments"].ToString();

table.Cell(tableRow + 1, 1).Range.Bold = 0;

table.Cell(tableRow + 1, 2).Range.Text = "..." + dsComments.Tables[0].Rows[i]["EnclouserNo"].ToString();

table.Cell(tableRow + 1, 2).Range.Bold = 0;

string imgUrl =”image Url”;

table.Rows.Add(ref objNull);

table.Rows.Add(ref objNull);

Range rngPic = table.Cell(tableRow + 2, 1).Range;

rngPic.InlineShapes.AddPicture(imgUrl, ref nullObj, ref nullObj, ref nullObj);

rngPic.InlineShapes[1].Height = 100F;

rngPic.InlineShapes[1].Width = 130F;

rngPic.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

// table.Cell(tableRow + 3, 1).Range.InlineShapes.AddPicture(imgUrl, ref myFalse, ref myTrue, ref nullObj);

table.Cell(tableRow + 3, 1).Range.Text = "Date :" + Convert.ToDateTime(dsComments.Tables[0].Rows[i]["CreatedDate"].ToString()).ToShortDateString() + " ";

table.Cell(tableRow + 3, 1).Range.Bold = 1;

table.Cell(tableRow+3, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

tableRow += 4;

}


1 comments:

Unknown said...

i find nastyness in the code...be compact and precise in code.