在C#中的MS Word文档的不同页面添加形状

时间:2013-06-03 08:18:24

标签: c# ms-word anchor

我目前正在使用Visual Studio 2010中的.NET应用程序。我想使用C#创建一个MS Word 2010文件。我已经创建了一个新文档并插入了一些段落。现在我想在文档中插入一些形状。因此,我使用Microsoft.Office.Interop.Word命名空间中的Word.Document.Shapes.AddLine() - 方法。我想在某些段落之后添加形状。当这些段落在文档的第一页上时,一切正常。但如果段落在另一页上,则形状也将插入第一页。我使用以下C#代码:

//Add paragraph
Word.Paragraph oPara2;
object oRng = NewDocument.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara2= NewDocument.Content.Paragraphs.Add(ref oRng);
oPara2.Range.Text = "Text";      
oPara2.Range.InsertParagraphAfter();

//Vertical position of the shape
float position = (float) (oPara2.Range.get_Information (Word.WdInformation.wdVerticalPositionRelativeToPage) - 16.5 );
//Add Line
Word.Shape line2 = NewDocument.Shapes.AddLine(30, position, 800, position);

/* 
*
*Some more paragraphs
*
**/
//Next Paragraph with shape
Word.Paragraph oPara13;
oRng = NewDocument.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara13 = NewDocument.Content.Paragraphs.Add(ref oRng);
oPara13.Range.Text = "Text";      
oPara13.Range.InsertParagraphAfter();

//Vertical position of the shape
position = (float) (oPara13.Range.get_Information (Word.WdInformation.wdVerticalPositionRelativeToPage) - 16.5 );
//Add Line
Word.Shape line3 = NewDocument.Shapes.AddLine(30, position, 800, position);

oPara13段落在文件的第二页。计算出的位置值是正确的,但形状将插入此位置的第一页。现在我想问一下如何将形状插入相应段落所在的正确页面。我已经尝试设置AddLine方法的锚参数,但结果不好。

2 个答案:

答案 0 :(得分:1)

首先,如果你需要的是使用OpenXML项目生成.docx文件,cosider。它的工作速度要快得多,并且不会遇到与使用Word相关的问题(如多线程,文件未正确关闭或许可)。使用OpenXML生成文档并非易事,但如果使用生产力工具,它会变得更加容易 - 它允许您打开任何文档并生成可重新创建它的c#代码。

关于你的问题,word会将它准确地插入到你提出的位置 - 函数会收到一个绝对的垂直坐标,你提供的坐标指向第一页。 所以不使用wdVerticalPositionRelativeToPage而是使用wdVerticalPositionRelativeToTextBoundary,在普通正常文本的情况下,它会给你绝对坐标。或者你可以得到最后一段的位置

absoluteY= ActiveDocument.Paragraphs(ActiveDocument.Paragraphs.Count).Range.Information(wdVerticalPositionRelativeToTextBoundary)  

ActiveDocument.Shapes.AddLine(50, absoluteY, 150, absoluteY).Select

另一个注意事项 - 如果您不确定如何执行某些操作,请打开Word并录制您执行此操作的宏。生成的代码非常有启发性。你会注意到Word经常使用select和Selection。

答案 1 :(得分:-1)

这个答案对我不起作用。但我做了一些研究并找到了这个解决方案:

方法Shapes.AddLine使用已知的4个参数坐标。但是有第五个参数。这是锚!

在这种情况下,Anchor是文本段落的新范围。 它总是占用当前页面的第一段。从那里你可以添加新的坐标:

ActiveDocument.Shapes.AddLine(x1, y1, x2, y2, <your paragraph>.Range).Select;