I am struggling since many days trying to solve this problem but I can't figure it out. I hope you can help me.
As you can see I am trying to add an image where the image width is always larger than the image height (all of them are "*.png"'s). My goal is it, to add this image in the top left of the page in proportion, so if in case the image is too big, the code will resize it to a proper size.
But my problem is, that I cannot figure out on how to add my image in the header. The image resizing would be another problem for me.
If possible, can I add a new image to the current header? If not, then adding a complete new page header would be ok for me.
What am I using?
In Visual Studio I am using the DocumentFormat
like this:
using DocumentFormat.OpenXml;
I also have some templates (*.dotx), where I actually am getting these templates and on these templates I would like to add these images to create my document.
What did I try?
I already have seen this post here:
Insert picture to header of Word document with OpenXML
... which actually my code is more or less based on.
private static void addHeaderToDocument(WordprocessingDocument wordDocument, MainDocumentPart mainDocumentPart, string relativeLogoFile)
{
var newHeaderPart = mainDocumentPart.AddNewPart<HeaderPart>();
var imagePart = headerPart.AddImagePart(ImagePartType.Png, "rId999");
var imagePartID = headerPart.GetIdOfPart(imagePart);
GetImageFromFile(imagePart, relativeLogoFile);
var rId = mainDocumentPart.GetIdOfPart(headerPart);
var headerRef = new HeaderReference { Id = rId };
var sectionProps = wordDocument.MainDocumentPart.Document.Body.Elements<SectionProperties>().LastOrDefault();
if (sectionProps == null)
{
sectionProps = new SectionProperties();
wordDocument.MainDocumentPart.Document.Body.Append(sectionProps);
}
sectionProps.RemoveAllChildren<HeaderReference>();
sectionProps.Append(headerRef);
headerPart.Header = GeneratePicHeader(imagePartID);
headerPart.Header.Save();
}
private static ImagePart GetImageFromFile(ImagePart imagePart, string relativeLogoFile)
{
using (FileStream stream = new FileStream(HttpContext.Current.Server.MapPath("~/" + relativeLogoFile), FileMode.Open))
{
imagePart.FeedData(stream);
}
return imagePart;
}
What exactly happens when you run this code?
Actually, running this code does add the image in the header, but not in the first page instead the image will be added in the second page, which really confuses me!
Do you have any ideas and suggestions what do here? Am I doing something wrong? Or could be the error something with my .dotx file?
What is the best way to do that? Should I remove first the header, then adding the image in the header (in the top right I already have an image which is in the *.dotx file)?
I hope you can help me with this problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.