Search code examples
c#.netwpfms-wordoffice-interop

Formatting a Word document using interop c#


I am currently trying to add an image, text and then another image. However when I insert the text the first image gets replaced.

var footer = document.Content.InlineShapes.AddPicture(AppDomain.CurrentDomain.BaseDirectory + "Images\\footer.png").ConvertToShape();
footer.WrapFormat.Type = WdWrapType.wdWrapTopBottom;
document.Content.Text = input;
var header = document.Content.InlineShapes.AddPicture(AppDomain.CurrentDomain.BaseDirectory+"Images\\header.png").ConvertToShape();
header.WrapFormat.Type = WdWrapType.wdWrapTopBottom;

How do I keep both images in my document?

Update With Rene's answer this is how the document is being presented. enter image description here


Solution

  • The property Content is a Range object that covers the complete document. A Range object holds all the stuff that is added.

    Setting the Text property replaces all content of the Range including non text-objects.

    To insert text and images in a cooperative way use the InsertAfter method, like so:

    var footer = document
        .Content
        .InlineShapes
        .AddPicture(AppDomain.CurrentDomain.BaseDirectory + "Images\\footer.png")
         .ConvertToShape();
    footer.WrapFormat.Type = WdWrapType.wdWrapTopBottom;
    
    // be cooperative with what is already in the Range present
    document.Content.InsertAfter(input);
    
    var header = document
        .Content
        .InlineShapes
        .AddPicture(AppDomain.CurrentDomain.BaseDirectory+"Images\\header.png")
        .ConvertToShape();
    header.WrapFormat.Type = WdWrapType.wdWrapTopBottom;
    

    If you want to have more control over where you content appears, you can introduce paragraphs, where each paragraph has its own Range. In that case your code could look like this:

    var footerPar = document.Paragraphs.Add();
    var footerRange = footerPar.Range;
    var inlineshape = footerRange.InlineShapes.AddPicture(AppDomain.CurrentDomain.BaseDirectory + "footer.png");
    var footer = inlineshape.ConvertToShape();
    footer.Visible = Microsoft.Office.Core.MsoTriState.msoCTrue;
    footer.WrapFormat.Type = WdWrapType.wdWrapTopBottom;
    
    var inputPar = document.Paragraphs.Add();
    inputPar.Range.Text = input;
    inputPar.Range.InsertParagraphAfter();
    
    var headerPar = document.Paragraphs.Add();
    var headerRange = headerPar.Range;
    var headerShape = headerRange.InlineShapes.AddPicture(AppDomain.CurrentDomain.BaseDirectory + "header.png");
    var header = headerShape.ConvertToShape();
    header.Visible = Microsoft.Office.Core.MsoTriState.msoCTrue;
    header.WrapFormat.Type = WdWrapType.wdWrapTopBottom;