We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

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);
        image.ImageInfo.File = source.FullName;
        image.ImageInfo.ImageFileType = GetImageFileType(source);
        image.ImageInfo.Title = source.Name;

        if (image.ImageWidth > image.ImageHeight)
    }</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 new DOM approach for converting image to PDF and check following code snippet to set page size as per image size. Hopefully it will help you to accomplish the task.

// Instantiate Document Object<o:p></o:p>

Aspose.Pdf.Document doc = new Aspose.Pdf.Document();

// Add a page to pages collection of document

Aspose.Pdf.Page page = doc.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 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 paragraphs collection of the section


// Set the image file stream

image.ImageStream = mystream;

// Save resultant PDF file


// Close memoryStream object


Please feel free to contact us for any further assistance.

Best Regards,