使用 interop c# 格式化 Word 文档

Formatting a Word document using interop c#

我目前正在尝试添加图像、文本,然后再添加图像。但是,当我插入文本时,第一张图片会被替换。

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;

如何在我的文档中保留这两个图像?

更新 Rene 的回答就是文件的呈现方式。

属性 Content 是一个涵盖整个文档的 Range 对象。 Range 对象包含所有添加的内容。

设置 Text 属性 替换 Range 的所有内容,包括非文本对象。

要以合作方式插入文本和图像,请使用 InsertAfter 方法,如下所示:

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;

如果您想更好地控制内容的显示位置,可以引入段落,每个段落都有自己的 Range。在这种情况下,您的代码可能如下所示:

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;