I want to format a table with horizontal center alignment for header row, and left alignment for content rows. But it only work for on the first cell on header row, code shown below:
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.StartTable();
BorderCollection borders = builder.CellFormat.Borders;
borders.LineStyle = LineStyle.Single;
borders.LineWidth = 0.5;
borders.Color = System.Drawing.Color.Gray;
// Insert a table row header
Cell cell = builder.InsertCell();
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; string s = "This is row 1 cell 1";
//cell.CellFormat.Width = s.Length;
cell.CellFormat.Width = 300;
builder.Write(s);
builder.InsertCell();
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; //not working
builder.Write("This is row 1 cell 2");
builder.EndRow();
//insert table content row
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
// Insert a cell
cell = builder.InsertCell();
builder.Writeln("This is row 2 cell 1");
// Insert a cell
builder.InsertCell();
builder.Writeln("This is row 2 cell 2");
builder.EndRow();
builder.EndTable();
// Save the document.
doc.Save(MapPath("Inserting a Table.doc"));
Hi Steve,
Thanks for your request. The problem occurs because in your code you reset alignment before starting a new cell. I modified your code and now it works as expected:
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.StartTable();
BorderCollection borders = builder.CellFormat.Borders;
borders.LineStyle = LineStyle.Single;
borders.LineWidth = 0.5;
borders.Color = System.Drawing.Color.Gray;
// Insert a table row header
Cell cell = builder.InsertCell();
cell.CellFormat.Width = 300;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
string s = "This is row 1 cell 1";
builder.Write(s);
builder.InsertCell();
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; //not working
builder.Write("This is row 1 cell 2");
builder.EndRow();
// Insert a cell
builder.InsertCell();
// insert table content row
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Writeln("This is row 2 cell 1");
// Insert a cell
builder.InsertCell();
builder.Writeln("This is row 2 cell 2");
builder.EndRow();
builder.EndTable();
// Save the document.
doc.Save(@"Test001\out.doc");
I highlighted part of code I moved after InsertCell.
Best regards,