I had a need to put an image into a MigraDoc table. The problem was that if the image was to large for the cell, it would spill over and off the page, plus I didn't want to resize it if it wasn't too big. When trying to inspect the image to find out the width and height, it would always return 0 for both. In case it might help someone else, here is how I resolved the issue.
Code:
private void AddRow2() {
var row = table.AddRow();
row.Shading.Color = TableWhite;
//row.HeightRule=RowHeightRule.Exactly;
//row.Height = 680;
var cellParagraph = row.Cells[0].AddParagraph();
//the diagrampath points to a picture
var image = cellParagraph.AddImage(viewModel.DiagramPath);
//because image.width/height always = 0 I had to do this
var imageScaling = CalculateImageScaling();
if (imageScaling == null) { return; }
image.ScaleHeight = imageScaling.Value;
image.ScaleWidth = imageScaling.Value;
}
private double? CalculateImageScaling() {
float horizontalResolution;
float verticalResolution;
//gets the users screen resolution
using (var panel = new Panel()) {
using (var g = panel.CreateGraphics()) {
horizontalResolution = g.DpiX;
verticalResolution = g.DpiY;
}
}
//bring the image in as a GDI+ object
var image = new Bitmap(viewModel.DiagramPath);
//calculate the points size of the image
var ptsWidth = image.Width * (72/horizontalResolution );
var ptsHeight = image.Height * (72/verticalResolution);
//do nothing if the image will fit in the cell
if (ptsHeight < 680 && ptsWidth < 576 ) { return null; }
//return the scalingFactor of the dimension that sticks out furthest
// in points 576 is the cell width, 680 is the cell height
var widthDiff = ptsWidth - 576;
var heightDiff = ptsHeight - 680;
if (heightDiff > widthDiff) { return 680 / ptsHeight ; }
return 576 / ptsWidth ;
}