With MigraDoc I'm trying to put a table in the center of the page. I'm using this code (c#, VS).
Section secondPage = new Section();
Table table = new Table();
AddColumns(table);
AddFirstRow(table);
AddSecondRow(table);
table.Format.Alignment=ParagraphAlignment.Center;
secondPage.Add(table);
I get a table aligned to the right of the page; how can I obtain a table in the center of the page?
To center a table in the center of a section.
table.Rows.Alignment = RowAlignment.Center;
You can set table.Rows.LeftIndent to indent the table. To get a centered table, calculate the indent based on paper size, page margins, and table width.
Example: Paper size is A4 (21 cm wide), left and right margins are 2.5 cm each. Thus we have a page body of 16 cm.
To center a table that is 12 cm wide, table.Rows.LeftIndent must be set to 2 cm (16 cm body width minus 12 cm table width gives 4 cm remaining space - half of the remaining space must be set as the LeftIndent).
From the code snippet in the original question, remove table.Format.Alignment=ParagraphAlignment.Center;
and replace it with table.Rows.LeftIndent="2cm";
.
Note that this will also work if the table is slightly wider than the body, but still within page edges. Using the page setup from the previous example, a table that is 18 cm wide can be centered with a LeftIndent of -1 cm.
Sample code (the table has just a single column):
var doc = new Document();
var sec = doc.AddSection();
// Magic: To read the default values for LeftMargin, RightMargin &c.
// assign a clone of DefaultPageSetup.
// Do not assign DefaultPageSetup directly, never modify DefaultPageSetup.
sec.PageSetup = doc.DefaultPageSetup.Clone();
var table = sec.AddTable();
// For simplicity, a single column is used here. Column width == table width.
var tableWidth = Unit.FromCentimeter(8);
table.AddColumn(tableWidth);
var leftIndentToCenterTable = (sec.PageSetup.PageWidth.Centimeter -
sec.PageSetup.LeftMargin.Centimeter -
sec.PageSetup.RightMargin.Centimeter -
tableWidth.Centimeter) / 2;
table.Rows.LeftIndent = Unit.FromCentimeter(leftIndentToCenterTable);
table.Borders.Width = 0.5;
var row = table.AddRow();
row.Cells[0].AddParagraph("Hello, World!");
The sample code uses Centimeter for calculations. You can also use Inches, Millimeter, Picas or Points. Default page size is A4 and in the sample the LeftIndent will be 4 cm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With