Free Support Forum - aspose.com

Center image relative to text

Hi,

I am inserting an image at a bookmark in a Word document using Aspose. These bookmarks will usually be within an existing sentence. The image will be a little higher than the actual text but needs to be centered vertically relative to the text.

See the attached document for the desired result. The fraction that appears after the word Answer: is the actual graphic that needs to be centered.

The following 2 lines of code, goes to my desired bookmark and then adds the graphic. Now I need to center it vertically.

How do I achieve this?

AsposeDoc.AsposeBuilder.MoveToBookmark(bkMark)

AsposeDoc.AsposeBuilder.InsertImage(_stagingDirectory & bkMark)

Thank You.

Hi Howard,


Thanks for your inquiry. Please use the following code snippet to achieve your requirements. Hope this helps you. Please let us know if you have any more queries.

Document doc = new
Document(MyDir + “in.docx”);<o:p></o:p>

DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToBookmark("bm");

builder.Write(" ");

Shape shape = builder.InsertImage(MyDir + "in.png");

shape.WrapType = WrapType.None;

shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Character;

shape.RelativeVerticalPosition = RelativeVerticalPosition.Paragraph;

shape.Top = -5;

builder.Write(" ");

doc.Save(MyDir + "out.docx");

Tahir,

Your code snippet worked perfectly.

Just one question, when I run my code, the image is now centered within the text but it is too close to the text. How do I place spaces before and after the image to make the sentence more readable?

Thank You!

Hi Howard,


Thanks for your inquiry. The following code snippet inserts the image with wrapping style as ‘In front of text’. In this case, I suggest you please add space after BookmarkStart and before BookmarkEnd nodes as shown in following code snippet. This will solve your problem. Please let us know if you have any more queries.


Document doc = new
Document(MyDir + “in.docx”);

DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToBookmark("bm");

Shape shape = builder.InsertImage(MyDir + "in.png");

shape.WrapType = WrapType.None;

shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Character;

shape.RelativeVerticalPosition = RelativeVerticalPosition.Paragraph;

shape.Top = -5;

Run run = new Run(doc);

run.Text = " ";

doc.Range.Bookmarks["bm"].BookmarkStart.ParentNode.InsertAfter(run.Clone(true), doc.Range.Bookmarks["bm"].BookmarkStart);

doc.Range.Bookmarks["bm"].BookmarkEnd.ParentNode.InsertBefore(run.Clone(true), doc.Range.Bookmarks["bm"].BookmarkEnd);

doc.Save(MyDir + "out.docx");