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

0
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
1 Comments
Order By: Standard | Newest | Votes
0
jles posted this 11 March 2020

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

155 Posts
295 Points

Our 228915 members have posted 344 times in 102 discussions