c# - 使用互操作 C# 格式化 Word 文档

标签 c# .net wpf ms-word office-interop

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

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 的回答就是文档的呈现方式。 enter image description here

最佳答案

属性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/

相关文章:

c# - Microsoft.AspNetCore.Hosting 的 System.BadImageFormatException

c# - .NET Multiline TextBox - 设置行数

c# - WPF Z 索引问题

WPF ContextMenu 使用 ItemsControl,错误地突出显示整个集合

wpf - 如何使 WPF 应用程序在 Web 浏览器上运行

c# - 从大型 XML 文件中删除节点

c# - 创建一个 TestServer 并使用 XUnit 和 ASP.NET Core 1.0 的依赖注入(inject)

c# - 异常抛出 : read access violation. 这是 0xBF13D000

c# - 如何在保存到数据库之前维护唯一列表? - C#

wpf - 如何在我的 ViewModel 中链接(依赖)属性?