Hi team, I need help to insert image in a table present in header. Condition is image can be present or not. If image is not there then image must be added or else ignored.
I have attached input and ouput sample doc.header_input.docx (20.0 KB)
header_output.docx (22.7 KB)
@tanzeel123 you can use the following code to achieve your goal, if you want to now more about how to work with Header/Footer please follow this link:
public void Main()
{
string imgSrc = "C:\\Temp\\logo.jpg";
if (!File.Exists(imgSrc))
{
return;
}
Document doc = new Document("C:\\Temp\\input.docx");
Document clonDoc = (Document)doc.Clone(true);
DocumentBuilder builder = new DocumentBuilder(clonDoc);
int sectionIndex = 0;
foreach (Section sec in clonDoc.Sections)
{
builder.MoveToSection(sectionIndex++);
// Set Primary Footer, because is the default
CheckAndAddImgInFirstCell(HeaderFooterType.HeaderPrimary, sec, builder, imgSrc);
// Check if First Footer is different and set it
if (sec.PageSetup.DifferentFirstPageHeaderFooter)
{
CheckAndAddImgInFirstCell(HeaderFooterType.HeaderFirst, sec, builder, imgSrc);
}
// Check if Footer is different in odd and even pages and set it
if (sec.PageSetup.OddAndEvenPagesHeaderFooter)
{
CheckAndAddImgInFirstCell(HeaderFooterType.HeaderEven, sec, builder, imgSrc);
}
}
clonDoc.Save("C:\\Temp\\output.docx");
}
public void CheckAndAddImgInFirstCell(HeaderFooterType headerType, Section sec, DocumentBuilder builder, string imgSrc)
{
HeaderFooter header = sec.HeadersFooters.FirstOrDefault(hf => ((HeaderFooter)hf).IsHeader && ((HeaderFooter)hf).HeaderFooterType == headerType) as HeaderFooter;
if (header != null)
{
Table table = header.GetChild(NodeType.Table, 0, true) as Table;
if (table != null)
{
if (table.FirstRow.FirstCell.ChildNodes.Count != 1
|| table.FirstRow.FirstCell.FirstParagraph.ChildNodes.Count != 1
|| table.FirstRow.FirstCell.FirstParagraph.FirstChild.NodeType != NodeType.Shape)
{
table.FirstRow.FirstCell.RemoveAllChildren();
builder.MoveToHeaderFooter(headerType);
builder.MoveTo(table);
builder.MoveToCell(0, 0, 0, 0);
builder.InsertImage(imgSrc, RelativeHorizontalPosition.Page, 0, RelativeVerticalPosition.Page, 0, 134, 115, WrapType.TopBottom);
}
}
}
}