我正在使用Micorosft Word Interop从C#生成Word文档。
我想在每个页面的标题中插入一些图像。我可以使用以下代码在每个页面上成功完成:
string imgHeader1 = "C:/image1.jpg";
foreach (Section section in document.Sections)
{
HeaderFooter header = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
header.Range.ParagraphFormat.SpaceAfter = 96;
header.Shapes.AddPicture(imgHeader1, 0, 1, 0, -40, 120, 20);
}
现在我想做同样的事情,但不是在第一页上。 我的建议如下:
document.PageSetup.DifferentFirstPageHeaderFooter = -1; //True
string imgHeader1 = "C:/image1.jpg";
foreach (Section section in document.Sections)
{
HeaderFooter header = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
//wdHeaderFooterFirstPage would be for first page..
header.Range.ParagraphFormat.SpaceAfter = 96;
header.Shapes.AddPicture(imgHeader1, 0, 1, 0, -40, 120, 20);
}
问题是图像仍然出现在第一页而不是第二页。
如果我查看此问题的答案Different First Page in a document using microsoft office interop word in c#并将代码复制到我的项目中,则文本显示在右侧标题上,但它似乎不适用于图像(?)
答案 0 :(得分:1)
以下适用于我。我为文档中的每个部分设置了DifferentFirstPage,应用格式,插入一些测试文本,插入图像。 (请注意,我的解决方案中有using Word = Microsoft.Office.Interop.Word
,因此来自Word对象模型的对象以Word.
开头
string imgHeader1 = "C:/image1.jpg";
foreach (Word.Section section in document.Sections)
{
section.PageSetup.DifferentFirstPageHeaderFooter = -1;
Word.HeaderFooter header = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
//wdHeaderFooterFirstPage would be for first page..
header.Range.ParagraphFormat.SpaceAfter = 96;
header.Range.Text = "test";
header.Shapes.AddPicture(imgHeader1, 0, 1, 0, -40, 120, 20);
}
答案 1 :(得分:0)
使用InlineShapes对象并在完成诀窍之后应用resizing和positiong。
Shape shape = header.Range.InlineShapes.AddPicture(imgHeader1, 0, 1, header.Range).ConvertToShape();
shape.Left = -1;
shape.Top = -42;
shape.Width = 275;
shape.Height = 151;
答案 2 :(得分:-1)
如果是第一页,我建议使用像check这样的东西。如果为true,则不执行任何其他操作