Hi there,
I want to insert a image with Picture class. What property do I need to setup for the image to make it either use its original size or fit to the page?
Hi there,
I want to insert a image with Picture class. What property do I need to setup for the image to make it either use its original size or fit to the page?
Hi Rico,
Please see the snippet below. You need to resize the Picture according to the page body width (which needs to be calculated). Please let me know if this helps.
public static void AddPicture()
{
// Load the document to add the Picture to.
Document document;
using (FileStream fileStream = File.Open(TestBase.WordDocumentsPath + @"Test1.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
document = Document.Load(fileStream);
}
// Add a Picture.
{
// Create the Picture element.
ImageData imageData = ImageData.FromBytes(File.ReadAllBytes(TestBase.WordDocumentsPath + @"Bird.jpg"));
Picture picture = new Picture(imageData, true);
// Calculate the size so that it will strach the page column width.
Section firstSection = document.Sections[0];
PageSize pageSize = firstSection.PageSetup.PageSize;
PageMargins pageMargins = firstSection.PageSetup.PageMargins;
Length bodyWidth = pageSize.Width - (pageMargins.Left + pageMargins.Right);
double pictureResizeFactor = bodyWidth.Points / picture.Width.Points;
picture.Width *= pictureResizeFactor;
picture.Height *= pictureResizeFactor;
document.Body.Elements.Add
(
new Paragraph
(
new Run(picture)
)
);
}
TestBase.TryDeleteFile(TestBase.WordDocumentsPath + @"Test1.pdf");
document.Save(TestBase.WordDocumentsPath + @"Test1.pdf");
}
Best regards, Jure
Last edited 11 March 2020