Hamish Grubijan
Hamish Grubijan

Reputation: 10820

How to insert a picture/text label at specific coordinates in a word 2007 document using C#?

I can do this to insert picture and text at a default location:

        private static object objTrue = true;
        private static object objFalse = false;
        private static object objMissing = Missing.Value;
        private static object objEndOfDoc = @"\endofdoc"; // \endofdoc is a predefined bookmark.

        ...

        this.WordApp = new Word.Application();
        this.WordDoc = new Word.Document();
        this.WordApp.Visible = true;
        this.WordDoc = this.WordApp.Documents.Add(ref objMissing, ref objMissing, ref objMissing, ref objMissing);

        this.WordDoc.Content.InlineShapes.AddPicture(
        FileName: @"C:\MyLogo.png",
        LinkToFile: ref objMissing,
        SaveWithDocument: ref objTrue,
        Range: objMissing);

        // Insert a paragraph at the beginning of the document.
        var paragraph1 = this.WordDoc.Content.Paragraphs.Add(ref objMissing);
        paragraph1.Range.Text = "Heading 1";
        paragraph1.Range.Font.Bold = 1;
        paragraph1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
        paragraph1.Range.InsertParagraphAfter();

How can I move it to any location I want? When I am creating PowerPoint (manually), I can position stuff anywhere. When I manually insert a shape, I can position it anywhere. How can I achieve similar result when inserting pictures and text labels programmatically using c#? I have not had success figuring this out using Google searches.

Upvotes: 3

Views: 5954

Answers (1)

Christopher Currens
Christopher Currens

Reputation: 30695

The Range class is used in word to determine where almost everything goes in a document. If you replaced the Range parameter in this.WordDoc.Content.InlineShapes.AddPicture with a valid Range object, it would insert the picture at that place in the word document, and the same goes for paragraphs.

According to MSDN for the AddPicture method on InlineShapes:

Range: Optional Object. The location where the picture will be placed in the text. If the range isn't collapsed, the picture replaces the range; otherwise, the picture is inserted. If this argument is omitted, the picture is placed automatically.

Another way would be to use the Shapes member of the document instead of InlineShapes. The AddPicture method on the Shapes class allows you to specify the coordinates:

this.WordDoc.Content.Shapes.AddPicture(
    [In] string FileName, 
    [In, Optional] ref object LinkToFile, 
    [In, Optional] ref object SaveWithDocument, 
    [In, Optional] ref object Left, 
    [In, Optional] ref object Top, 
    [In, Optional] ref object Width, 
    [In, Optional] ref object Height, 
    [In, Optional] ref object Anchor
);

InlineShapes.AddPicture

Shapes.AddPicture

Upvotes: 6

Related Questions