Setting page orientation of generated PDF based on width and height of inserted image

Hi there,



I’m trying to set the page orientation of the generated PDF based on the size of an image I insert. If the width is greater than the height, I’d like to flip to landscape aspect ratio.

Here’s my code:

        public override void Convert(FileInfo source, FileInfo target)
{
Pdf pdf = new Pdf();
        Section section = pdf.Sections.Add();
        var image = new Image(section);
        section.Paragraphs.Add(image);
        image.ImageInfo.File = source.FullName;
        image.ImageInfo.ImageFileType = GetImageFileType(source);
        image.ImageInfo.Title = source.Name;

        if (image.ImageWidth > image.ImageHeight)
        {
            FlipToLandscapeOrientation(section);
        }
        
        pdf.Save(target.FullName);
    }</pre></div><div><br></div><div>The problem here is that <b>FlipToLandscapeOrientation()</b> is never called because <b>image.ImageWidth</b> and <b>image.ImageHeight</b> are always <b>0</b>.</div><div><br></div><div>How can I force these to populate with the real width and height of the image I've supplied?</div><div><br></div><div><br></div><div>Many thanks,</div><div><br></div><div><br></div><div>Bart</div>

Hi Bart,

Thanks for your inquiry. Please use the new DOM approach for converting image to PDF and check the following code snippet to set the page size as per the image size. Hopefully, it will help you to accomplish the task.

// Instantiate Document Object
Aspose.Pdf.Document document = new Aspose.Pdf.Document();

// Add a page to the pages collection of the document
Aspose.Pdf.Page page = document.Pages.Add();

// Load the source image file to Stream object
FileStream fs = new FileStream("c:/pdftest/logo.jpg",
    FileMode.Open, FileAccess.Read);

byte[] tmpBytes = new byte[fs.Length];
fs.Read(tmpBytes, 0, Convert.ToInt32(fs.Length));

MemoryStream mystream = new MemoryStream(tmpBytes);

// Instantiate Bitmap object with loaded image stream
Bitmap b = new Bitmap(mystream);

// Set margins so the image will fit, etc.
page.PageInfo.Margin.Bottom = 0;
page.PageInfo.Margin.Top = 0;
page.PageInfo.Margin.Left = 0;
page.PageInfo.Margin.Right = 0;

// Create an image object
Aspose.Pdf.Image image = new Aspose.Pdf.Image();

//image.FixWidth = b.Width;
//image.FixHeight = b.Height;

page.PageInfo.Width = b.Width;
page.PageInfo.Height = b.Height;

// Add the image into the paragraphs collection of the section
page.Paragraphs.Add(image);

// Set the image file stream
image.ImageStream = mystream;

// Save the resultant PDF file
document.Save("c:/pdftest/Image2PDF_DOM.pdf");

// Close the MemoryStream object
mystream.Close();

Please feel free to contact us for any further assistance.

Best Regards,