3

Is there a way to add a border around the table and hide the cell borders in MigraDoc?

user629283
  • 329
  • 1
  • 8
  • 23

2 Answers2

6

The default width of the borders is 0 and borders are not visible. To enable borders, set a value greater than 0.

If table is your Table object, you could write table.Borders.Width = 0.5;

You can set borders for the table and for each cell. Cells inherit border properties from the table, the column, the row unless they are overwritten at a lower stage.

Also check the SetEdge method of the Table class.

Sample code discussed here:
http://www.pdfsharp.net/wiki/Invoice-sample.ashx

My test code:

private static void TabelWithBorderTest()
{
    var document = new Document();

    // Add a section to the document.
    var section = document.AddSection();

    Table table = section.AddTable();
    table.Borders.Width = 0.25;
    table.Rows.LeftIndent = 0;

    // Before you can add a row, you must define the columns
    Column column = table.AddColumn("7cm");
    column.Format.Alignment = ParagraphAlignment.Left;

    Row row = table.AddRow();
    row.Cells[0].AddParagraph("Text in table");

    // Create a renderer for the MigraDoc document.
    var pdfRenderer = new PdfDocumentRenderer(false) { Document = document };

    // Associate the MigraDoc document with a renderer.

    // Layout and render document to PDF.
    pdfRenderer.RenderDocument();

    // Save the document...
    const string filename = "TableTest.pdf";
    pdfRenderer.PdfDocument.Save(filename);
    // ...and start a viewer.
    Process.Start(filename);
}
2

I managed to get this down by setting each row borders visibility as false;

  var document = new Document();
  var page = document.AddSection();
  Table table = page.AddTable();
  table.Borders.Visible = true;
  Column col = table.AddColumn("3cm");
  col = table.AddColumn("10cm");
  col = table.AddColumn("3cm");
  col.Format.Alignment = ParagraphAlignment.Left;
  Row row = table.AddRow();
  Paragraph p = row.Cells[0].AddParagraph();
  p.AddFormattedText("Top header row");
  row.Cells[0].MergeRight = 2;
  // then set it in visible as false like this, you can do top, left and right as well
  row.Cells[0].Borders.Bottom.Visible = false;

Doesn't look nice but if anyone has a better solution do post it up

user629283
  • 329
  • 1
  • 8
  • 23
  • My sample code works without setting the visibility - it works fine with the default values. What's the purpose of `p.AddFormattedText("Top header row");`? – I liked the old Stack Overflow Aug 17 '17 at 15:16
  • @PDFsharpNovice I tried that but it didn't work for me – user629283 Aug 18 '17 at 10:25
  • @PDFsharpNovice when i tried your way it removes all the border lines including the one around the table. p.addformattedText part - that was a quick copy and paste, but i was going to make that part bold. – user629283 Aug 18 '17 at 14:01