C# Word Automation: Inserting Images
I was looking for a way to insert images at a bookmark in a word document and thought should document these for future reference
CImage class Definition
public class CImage
{
public string Path
{
get;
set;
}
public decimal Id
{
get;
set;
}
public string Title
{
get;
set;
}
public Image Bitmap
{
get;
set;
}
public bool BusyLoading
{
get;
set;
}
public void GetImage()
{
try
{
BusyLoading = true;
WebRequest req = WebRequest.Create(Path);
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
Bitmap = Image.FromStream(stream);
stream.Close();
}
catch
{
Bitmap = null;
}
finally
{
BusyLoading = false;
}
}
}
Scenario 1:
You have a path of the image file which is to be inserted
public static void SetBookMark(Document p_objWordDocument, string p_strName,
CImage p_objImage)
{
if (p_objWordDocument.Bookmarks.Exists(p_strName))
{
object objBookMark = p_strName;
p_objWordDocument.Bookmarks.get_Item(ref objBookMark).Range.InlineShapes.AddPicture(p_objImage.Path, ... dozons of object params ...);
}
}
Scenario 2:
When you have the bitmap in memory
public static void SetBookMark(Document p_objWordDocument, string p_strName,
CImage p_objImage)
{
if (p_objWordDocument.Bookmarks.Exists(p_strName))
{
object objBookMark = p_strName;
Clipboard.SetDataObject(p_objImage.Bitmap);
p_objWordDocument.Bookmarks.get_Item(ref objBookMark).Range.Paste();
}
}
Important information
You need to add a COM reference to your favorite word object library which should in turn add
- Microsoft.Office.Core
- VBIDE
- Word
If you do not see these added, make sure you have PIAs for office version installed on your machine.
Get Office 2007 PIAs here
Get Office 2003 PIAs here
Related Posts
- C# Word Automation: Inserting images with text wrapping around
- C# Word Automation : How to add a Shape textbox
- C# Word Automation: Solve “The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)”
Advertisement
Categories: .NET
