Search code examples
c#imagepdfaspose

How to place images dynamically using Aspose.PDF in C#?


I have a C# script where I am using the Aspose.PDF library. I am trying to place multiple images with a bit of a spacing vertically.

Here is what I am doing.

  // Create pdf document
        Aspose.Pdf.Document document = new Aspose.Pdf.Document();
        Aspose.Pdf.Page page = document.Pages.Add();


        Aspose.Pdf.Text.TextFragment text = new Aspose.Pdf.Text.TextFragment("Einstein Picture");
        page.Paragraphs.Add(text);

        Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(100, 600, 300, 800);
        Aspose.Pdf.Rectangle rectangle1 = new Aspose.Pdf.Rectangle(100, 400, 300, 800);

        page.AddImage("C:/Users/Alan/Desktop/image.gif", rectangle);
        page.AddImage("C:/Users/Alan/Desktop/s.jpeg", rectangle1);


        document.Save("C:/Users/Alan/Desktop/Testpdf.pdf", Aspose.Pdf.SaveFormat.Pdf);

How can I perfectly align pictures vertically with a bit of gap no matter how many pictures there are?

Currently the picture looks like this. PDF image


Solution

  • I request you to use below code snippet on your end and then share your kind feedback with us. This will enable you to place multiple images with a bit vertical spacing.

            // Instantiate Document object
            var pdf = new Aspose.Pdf.Document();
            //Add a page to the document
            var pdfImageSection = pdf.Pages.Add();
            DirectoryInfo dir = new DirectoryInfo(@"D:\Aspose Files\images\");
            FileInfo[] files = dir.GetFiles("*.jpg");
            //Iterate through multiple images
            foreach (var file in files)
            {
                FileStream stream = new FileStream(file.FullName, FileMode.Open);
                System.Drawing.Image img = new System.Drawing.Bitmap(stream);
                var image = new Aspose.Pdf.Image { ImageStream = stream };
                //Set appearance properties
                image.FixHeight = 300;
                image.FixWidth = 300;
                //Set margins for proper spacing and alignment
                image.Margin = new MarginInfo(5, 5, 5, 5);
                //Add the image to paragraphs of the document
                pdfImageSection.Paragraphs.Add(image);
            }
            //Save resultant document
            pdf.Save(@"D:\Aspose Files\Image2Pdf_out.pdf");
    

    You were simply adding an image on a PDF page whereas this code snippet adds an image to Paragraphs collection and setting the margin property of image object fixes the alignment and spacing of the images.

    Please let us know if you need any further assistance. We will be glad to help. For Aspose documentation to manipulate images is here.

    I work with Aspose as Developer Evangelist.