Search code examples
c#imageepplus

C# EPPlus picture height getting stretch when placed into cell B1


I am trying to place a picture into B1 cell. picture is getting inserted but height is getting bigger than original image.

I am using EPPlus version 4.0.6.0 & .Net version 4.5.2. using VS IDE 2013.

Here is the output screenshot. enter image description here

Desired output screenshot enter image description here

here is the code sample which i used to place picture into B1 cell.

if (imgCompanyLogo != null)
{
    var picture = ws.Drawings.AddPicture("Test", imgCompanyLogo);
    int pixelHeight=GetHeightInPixels(ws.Cells[1,2]);
    int pixelWidth = GetWidthInPixels(ws.Cells[1, 2]);
    picture.SetSize(pixelWidth, pixelHeight);
    picture.SetPosition(0, 0, 1, 0);
}

Below code snippet taken from this post https://stackoverflow.com/a/50371532/15940620

private static int GetHeightInPixels(ExcelRange cell)
{
    using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
    {
        float dpiY = graphics.DpiY;
        return (int)(cell.Worksheet.Row(cell.Start.Row).Height * (1 / 72.0) * dpiY);
    }
}

public static float MeasureString(string s, Font font)
{
    using (var g = Graphics.FromHwnd(IntPtr.Zero))
    {
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

        return g.MeasureString(s, font, int.MaxValue, StringFormat.GenericTypographic).Width;
    }
}

private static int GetWidthInPixels(ExcelRange cell)
{
    double columnWidth = cell.Worksheet.Column(cell.Start.Column).Width;
    Font font = new Font(cell.Style.Font.Name, cell.Style.Font.Size, FontStyle.Regular);

    double pxBaseline = Math.Round(MeasureString("1234567890", font) / 10);

    return (int)(columnWidth * pxBaseline);
}

my problem is picture height is getting stretch after placing into B1 cell. i am not able to understand what i am missing in my code.

i also try to measure the height & width of picture in pixel like this way but still no luck.

decimal mdw = ws.Workbook.MaxFontWidth;
int pixelHeight = (int)(ws.Row(1).Height / 0.75);
int pixelWidth = (int)decimal.Truncate(((256 * (decimal)ws.Column(2).Width + decimal.Truncate(128 / (decimal)mdw)) / 256) * mdw);

Please advise me what is wrong in my approach for which picture's height is getting stretched. Thanks


Solution

  • My issue resolved.

    if (imgCompanyLogo != null)
    {
        var picture = ws.Drawings.AddPicture("Test", imgCompanyLogo);
        picture.EditAs = OfficeOpenXml.Drawing.eEditAs.TwoCell;
        picture.SetPosition(0, 0, 1, 0);
    }
    

    this line solved the problem. picture.EditAs = OfficeOpenXml.Drawing.eEditAs.TwoCell;

    but one thing not clear that why do i need to spread my image across two cell?

    Thanks