Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a table in the center of the page?

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?

like image 268
Martina Avatar asked Sep 24 '14 08:09

Martina


2 Answers

To center a table in the center of a section.

table.Rows.Alignment = RowAlignment.Center;
like image 79
Jason Portnoy Avatar answered Sep 20 '22 13:09

Jason Portnoy


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.

like image 33
I liked the old Stack Overflow Avatar answered Sep 18 '22 13:09

I liked the old Stack Overflow