Click here to Skip to main content
15,885,435 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have a Word document with a header for the first page and a header for the 2nd and next pages. Each of the two headers contain an image. These images must be replaced.

This piece of code works fine to remove all images.

C#
foreach (Word.Section section in objDocument.Sections)
{
  foreach (Word.HeaderFooter headerfooter in section.Headers)
  {
    Word.Shapes shapes = headerfooter.Shapes;
    for (int i = 0; i < shapes.Count; i++)
    {
      object item = i + 1;
      shape = shapes.get_Item(ref item);
      if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoEmbeddedOLEObject)
      {
        shapes.AddPicture(workparams.imagepath, ref linktofile, ref savewithdocument,
          ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);

        shape.Delete();
      }
    }
  }
}


But the images I add all show up in the header of the first page.

It probably has to do with the 'anchor' of the image, but I can't figure it out where to find the right anchor.

Does anybody know the trick to insert an image in the header on the second page?
Thanks...
Posted

I haven't played with images in headers, but I have done some automation with headers. The method I use is to use

Word.HeaderFooter headerfooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];


According to MSDN[^] wdHeaderFooterFirstPage indexes the header on the first page in the section whilst wdHeaderFooterPrimary accesses the header on the remaining pages in the section.
 
Share this answer
 
Thanks Graham, this pointed me in the right direction!

This is my solution.

C#
foreach (Word.Section section in objDocument.Sections)
{
  headerfooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage];
  try
  {
    for (int i = 0; i < headerfooter.Range.InlineShapes.Count; i++)
    {
      inlineshape = headerfooter.Range.InlineShapes[i + 1];
      inlineshape.Delete();
      headerfooter.Range.InlineShapes.AddPicture(workparams.imagepath, ref linktofile, ref savewithdocument, ref Unknown);
    }
  }
  catch (Exception ex)
  {
    throw;
  }


  headerfooter = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
  try
  {
    for (int i = 0; i < headerfooter.Range.InlineShapes.Count; i++)
    {
      inlineshape = headerfooter.Range.InlineShapes[i + 1];
      inlineshape.Delete();
      headerfooter.Range.InlineShapes.AddPicture(workparams.imagepath, ref linktofile, ref savewithdocument, ref Unknown);
    }
  }
  catch (Exception ex)
  {
    throw;
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900