2

Below code with spire.doc

var doc = new Document();
doc.LoadFromFile(@"E:\test.docx", FileFormat.Doc);
var image = Image.FromFile(@"E:\nice.jpg");
var picture1 = doc.Sections[0].Paragraphs[0].AppendPicture(image);
picture1.VerticalAlignment = ShapeVerticalAlignment.Top;
picture1.HorizontalAlignment = ShapeHorizontalAlignment.Left;
picture1.TextWrappingStyle = TextWrappingStyle.Square;
doc.SaveToFile(@"..\..\result.doc", FileFormat.Doc);
System.Diagnostics.Process.Start(@"..\..\result.doc");

How can I insert image and text into certain positions in a Word template using either the spire.doc or the Microsoft.Office.Interop.Word libraries?

Or similar this link with insert image to certain position in world template.

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Hossein Hagh
  • 127
  • 2
  • 3
  • 15

2 Answers2

0

using Microsoft.Office.Interop.Word,

first, you need to ensure the selection is in right position,

then, insert images, there are couple of options, here is my code,

If bInline Then
    Dim oInlineShape As InlineShape = m_oWordApp.Selection.InlineShapes.AddPicture(FileName:=sImageFilePath, LinkToFile:=False, SaveWithDocument:=True)
oInlineShape.Range.ParagraphFormat.Alignment = nAlignment
    If nHeight > 0 AndAlso nWidth > 0 Then
        oInlineShape.LockAspectRatio = MsoTriState.msoFalse
        oInlineShape.Height = nHeight
        oInlineShape.Width = nWidth
    End If
Else
    Dim oShape As Word.Shape = m_oWordApp.ActiveDocument.Shapes.AddPicture(Anchor:=m_oWordApp.Selection.Range, FileName:=sImageFilePath, LinkToFile:=False, SaveWithDocument:=True)
    If nHeight > 0 AndAlso nWidth > 0 Then
        oShape.LockAspectRatio = MsoTriState.msoFalse
        oShape.Height = nHeight
        oShape.Width = nWidth
    End If
End If

insert text is quite easy, you just need to ensure selection object is in right position, then,

m_oWordApp.Selection.Text = sMsg
'you can update background colors ....
m_oWordApp.Selection.Range.HighlightColorIndex = 0
'you update fonts ....
m_oWordApp.Selection.Font.Bold = True

Hope it helps.

Victor Xie
  • 148
  • 1
  • 9