Inserting Images larger than page size

I’ve run into an issue where, inserting a very large image into a document causes the image to bleed over the margin. I had this issue crop up with the PDF team and it was addressed here: <a href="Images don't adhere to margins

Here is a stripped down test case I threw together (Image is attached):

Aspose.Words.Document doc = new Aspose.Words.Document();
Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);
System.Drawing.Image img = System.Drawing.Image.FromFile("C:/test/test_image.png");
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
builder.InsertImage(ms);

doc.Save(@"C:/test/output.doc");

I do know that if I open Word, and Insert this same image, look to Print Preview, it shows just what Aspose exports. So… I’m not entirely sure how to approach this. Is there perhaps some option I need to flag that will force images to automatically resize to fit within the margins? Do I need to manually resize the image appropriately to fit within the specified margins?

Any help would be greatly appreciated.

Hi Philip,

Thanks for your inquiry. Sure, you can fit large image within the page bounds by using the following code snippet:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
System.Drawing.Image img = System.Drawing.Image.FromFile("C:/Temp/test_image.png");
double targetHeight;
double targetWidth;
CalculateImageSize(builder, img, out targetHeight, out targetWidth);
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
Shape image = builder.InsertImage(ms, targetWidth, targetHeight);
doc.Save(@"C:/Temp/out.doc");

public static void CalculateImageSize(DocumentBuilder builder, Image img, out double targetHeight, out double targetWidth)
{
    // Calculate width and height of the page
    PageSetup ps = builder.CurrentSection.PageSetup;
    targetHeight = ps.PageHeight - ps.TopMargin - ps.BottomMargin;
    targetWidth = ps.PageWidth - ps.LeftMargin - ps.RightMargin;
    // Get size of an image
    double imgHeight = ConvertUtil.PixelToPoint(img.Height);
    double imgWidth = ConvertUtil.PixelToPoint(img.Width);
    if (imgHeight <targetHeight && imgWidth <targetWidth)
    {
        targetHeight = imgHeight;
        targetWidth = imgWidth;
    }
    else
    {
        // Calculate size of an image in the document
        double ratioWidth = imgWidth / targetWidth;
        double ratioHeight = imgHeight / targetHeight;
        if (ratioWidth> ratioHeight)
            targetHeight = (targetHeight * (ratioHeight / ratioWidth));
        else
            targetHeight = (targetWidth * (ratioWidth / ratioHeight));
    }
}

I hope, this helps.

Best regards,