How to place a image with code approach with original size/occupy the whole width of the document?

RicoMM posted this 26 February 2020

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?

8 Posts
9 Points
Order By: Standard | Newest | Votes
jles posted this 4 weeks ago

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;

                new Paragraph
                    new Run(picture)

        TestBase.TryDeleteFile(TestBase.WordDocumentsPath + @"Test1.pdf");
        document.Save(TestBase.WordDocumentsPath + @"Test1.pdf");

Best regards, Jure

Last edited 4 weeks ago

119 Posts
246 Points

Our 31228 members have posted 271 times in 80 discussions