Anchoring a Shape in a Word Document (c#)

C

ChrisW123

Hi Everyone,

I'm using C# to insert images using the Shape object, and I'm runing into
problems trying to anchor the Shape after I add it. The problems are:

1) The code below inserts the Shape correctly only if I'm on the first page
of the document. If I'm on the second page (the cursor), the Shape will be
created in the right location, but on the first page! I need the shape on
the second page, where the cursor is.

2) If I try setting "anchor" to this.myWordApp.Selection.Range, I get
strange results. Sometimes the Shape is created, but it will be 2 inches
below the cursor. At other points in the document, the Shape is not created
at all. Very flaky behaviour when I set "anchor".

Here's the code I'm using. Any help would be greatly appreciated!

// Find the cursor location in the document. This is where we
// want to create the Shape object.
float leftPos = (float)this.myWordApp.Selection.get_Information(

Word.WdInformation.wdHorizontalPositionRelativeToTextBoundary);

float topPos = (float)this.myWordApp.Selection.get_Information(
Word.WdInformation.wdVerticalPositionRelativeToTextBoundary);

// Build our Shape parameters
string imageFilename =
@"C:\!Temp\DragDropSample\tag-sign-borrower.png";
object linkToFile = false;
object saveWithDoc = true;
object left = leftPos;
object top = topPos;
object anchor = missing; //this.myWordApp.Selection.Range;

// Add the Shape to the document.
Word.Shape shape = this.myWordDoc.Shapes.AddPicture(
imageFilename,
ref linkToFile,
ref saveWithDoc,
ref left,
ref top,
ref missing,
ref missing,
ref anchor);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top