简体   繁体   English

使用Interop C#格式化Word文档

[英]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. 使用Rene的答案进行更新,这就是文档的呈现方式。 在此处输入图片说明

The property Content is a Range object that covers the complete document. 属性Content是一个涵盖整个文档的Range对象。 A Range object holds all the stuff that is added. Range对象保存所有添加的内容。

Setting the Text property replaces all content of the Range including non text-objects. 设置Text属性将替换Range所有内容,包括非文本对象。

To insert text and images in a cooperative way use the InsertAfter method, like so: 要以协作方式插入文本和图像,请使用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;

If you want to have more control over where you content appears, you can introduce paragraphs, where each paragraph has its own Range . 如果您想更好地控制内容的显示位置,可以引入段落,其中每个段落都有自己的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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM