我目前正在尝试添加图像、文本,然后添加另一个图像。但是,当我插入文本时,第一个图像会被替换。
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;
如何将这两个图像保留在我的文档中?
最佳答案
属性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;
如果您想更好地控制内容的显示位置,您可以引入段落,其中每个段落都有自己的范围
。在这种情况下,您的代码可能如下所示:
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;
关于c# - 使用互操作 C# 格式化 Word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37853703/