I need to put an image in the center of a table's cell. When I add the image in a cell the image is aligned topleft. How can I align the image in the center of a cell?
Asked
Active
Viewed 6,960 times
4 Answers
29
You might need to add a paragraph to the cell, set the alignment on the paragraph, and then add the image to the paragraph.
row.Cells[0].Format.Alignment = ParagraphAlignment.Center;
row.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row.Cells[0].AddParagraph().AddImage(imageLocation);

Reuben
- 4,136
- 2
- 48
- 57
-
1Thanks! This worked for me. This should be marked as answer. – saurabhj Aug 10 '16 at 08:41
6
row.Cells[0].Format.Alignment = ParagraphAlignment.Center;
row.Cells[0].VerticalAlignment = VerticalAlignment.Center;

Jeff
- 1,364
- 1
- 8
- 17
-
2It doesn't work. I'm trying to do a different thing. I'm trying to set the width of the cell according with the size of the image. I'm using 'Column column = table.AddColumn(); column.Width = Image.FromFile(shotOfImplants).Width;' but I obtain a cell with a differnt size compared with the image "shotOfImplants". – Martina Oct 14 '14 at 09:04
-
3
-1
In my version of MigraDoc, Jeff and Reuben's solution does not work as shown: Setting the cell's Format.Alignment
property has no effect, even when the image is inside a paragraph.
However, what does work for me is to put the image in a paragraph, just as Jeff and Reuben say, then give the paragraph a named style which includes centering.
In my method which predefines all my styles, I do something like:
// Here we assume the "TableText" style has already been created
var sty = doc.Styles.AddStyle( "TableTextCenter", "TableText" );
sty.ParagraphFormat.Alignment = ParagraphAlignment.Center;
And at the point where I add the image, I do this:
var para = table.Cells[ 0 ].AddParagraph();
para.Style = "TableTextCenter"; // <----- This is the magic!
var img = para.AddImage( imageFileSpec );
img.LockAspectRatio = true;
img.Width = "4cm";
img.WrapFormat = new WrapFormat {
Style = WrapStyle.Through
};

Charles Jenkins
- 340
- 4
- 10
-1
As @Reuben says, what is interesting is:
row.Cells[0].AddParagraph().AddImage(imageLocation);
I was trying with
row.Cells[0].AddImage(imageLocation);
And the image was inserted in the document but I couln't get it centered.

David
- 59
- 4