Hello GemBox team,
I am trying to add the image to my docx file and then convert it to PDF.
As the footer and header size may vary depending on the content, I cannot find a way to calculate the size of the image to insert properly. Regardless of the content, the margins in Page Setup are always the same.
Is there a way to properly calculate the size of footers/headers or add the auto sizing of the image based on the page content?
If I add the image as is, it crops up to fit the document. I am not sure how to send the files properly, but I think it is easily reproducible with any rather big image.
I would be thankful for any advice
Thank you,
Oleksandr
Hi Oleksandr,
The only way to do this is to calculate the remaining space on the page, which is a bit tricky because it involves using the rendering engine.
For example, let’s say you have the following document:
Now, to calculate this area between the current default header and default footer, you would need something like this:
var document = DocumentModel.Load("input.docx");
var section = document.Sections[0];
var headerDefault = section.HeadersFooters[HeaderFooterType.HeaderDefault];
var footerDefault = section.HeadersFooters[HeaderFooterType.FooterDefault];
var page = document.GetPaginator().Pages[0];
var lastHeaderElementLayout = page.GetElementLayout(headerDefault.Blocks.Last());
var firstFooterElementLayout = page.GetElementLayout(footerDefault.Blocks.First());
var pageSetup = section.PageSetup;
double pageHeight = firstFooterElementLayout.VerticalPosition.Value
- firstFooterElementLayout.Size.Height
- lastHeaderElementLayout.VerticalPosition.Value;
double pageWidth = pageSetup.PageWidth
- pageSetup.PageMargins.Left
- pageSetup.PageMargins.Right;
And to add the resized Picture
, you would need something like this:
var picture = new Picture(document, "image.png");
var pictureLayout = picture.Layout;
var pictureSize = pictureLayout.Size;
double ratioX = pageWidth / pictureSize.Width;
double ratioY = pageHeight / pictureSize.Height;
double ratio = Math.Min(ratioX, ratioY);
if (ratio < 1)
pictureLayout.Size = new Size(pictureSize.Width * ratio, pictureSize.Height * ratio);
section.Content.End.InsertRange(picture.Content);
document.Save("output.docx");
The following is a screenshot of the resulting “output.docx” file:
I hope this helps.
Regards,
Mario
Hello Mario,
I have tried a similar approach by rendering it to PDF and then replacing the picture with a properly calculated one.
From your response, I can understand that there is no simple way of calculating the proper margins for the image. And since your version is more performant and elegant I will stick to it!
Thanks much for the quick reply!