Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在除第一页以外的每一页的页眉中添加图片_C#_.net_Ms Word_Office Interop - Fatal编程技术网

C# 在除第一页以外的每一页的页眉中添加图片

C# 在除第一页以外的每一页的页眉中添加图片,c#,.net,ms-word,office-interop,C#,.net,Ms Word,Office Interop,我正在使用Micorosft Word Interop从C#生成Word文档 我想在每页的页眉中插入一些图像。我可以使用以下代码在每个页面上成功完成此操作: string imgHeader1 = "C:/image1.jpg"; foreach (Section section in document.Sections) { HeaderFooter header = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];

我正在使用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);
}
问题是图像仍然出现在第一页而不是第二页


如果我查看这个问题的答案,并将代码复制到我的项目中,文本会出现在正确的标题上,但它似乎不适用于图像(?)

我建议使用类似“检查是否在第一页”的方法。如果为true,则不做任何其他操作使用该图像

以下内容适用于我。我为文档中的每个部分设置不同的第一页,应用格式,插入一些测试文本,插入图像。(注意,我的解决方案中有一个
使用Word=Microsoft.Office.Interop.Word
,因此Word对象模型中的对象前面有
Word。


使用InlineShapes对象并在为我完成该技巧后应用大小调整和定位

Shape shape = header.Range.InlineShapes.AddPicture(imgHeader1, 0, 1, header.Range).ConvertToShape();
shape.Left = -1;
shape.Top = -42;
shape.Width = 275;
shape.Height = 151;

尝试为循环中的每个部分设置DifferentFirstPage,因为文档显然有多个部分。DifferentFirstPage可以按节设置…这并没有改变任何内容。对于我来说,图像仍然出现在第一页上,那么文档的结构可能会有问题-节中断的位置。你确定这个“第一页”实际上是一个章节的第一页吗?“节”是指新的分页符?或者本页是否使用了“连续”分节符?在这种情况下,Word不会将其视为新部分的第一页,而是视为上一部分的最后一页。
Shape shape = header.Range.InlineShapes.AddPicture(imgHeader1, 0, 1, header.Range).ConvertToShape();
shape.Left = -1;
shape.Top = -42;
shape.Width = 275;
shape.Height = 151;