Search code examples
c#dynamicpdf

Adding a DataTable to Dynamic PDF


Dynamic PDF Example

I want to be able to read in a DataTable in C# and add it to a PDF file. The example shows how to do it one row at a time, but it appears you have to define each row in the table. I have not been able to figure out how to dynamically add the full DataTable to a grid. I have the looping setup, but since I have to add a new row each time it won't work. Example of my attempt found below.

        DataTable myDT = new DataTable();
        myDT = dbAccessObject.GetDTValues();//just filling DataTable


        // Create a PDF Document
        Document document = new Document();

        // Create a Page and add it to the document
        Page page = new Page();
        document.Pages.Add(page);

        // add Table to PDF
        // Create a table 
        Table table = new Table(20, 100, 600, 600);
        table.Columns.Add(100);
        table.Columns.Add(100);

        Row headers = table.Rows.Add(20, Font.Helvetica, 12);
        string colStr = "name";
        string colStr1 = "desc";
        headers.Cells.Add(colStr);
        headers.Cells.Add(colStr1);
        Row row = table.Rows.Add(20, Font.Helvetica, 12);
        Row row2 = table.Rows.Add(20, Font.Helvetica, 12);
        int i, j;
        i = j = 0;
        while (i < myDT.Rows.Count)
        {
            while(j<myDT.Columns.Count)
            {
            row.Cells.Add(myDT.Rows[i][j].ToString());//need a default row here or way to add directly to the table
                j++;}
            j = 0;
            i++;}


        // Add the table to the page
        page.Elements.Add(table);    


        // Add a label to the page 
        page.Elements.Add(new Label("New PDF Document", 0, 0, 512, 40, Font.Helvetica, 30, TextAlign.Center));


        // Save the PDF document
        document.DrawToWeb("MyDocument.pdf", true);

Solution

  • You have to specifically build and add the necessary elements to the current Page instance you are working with in DynamicPDF. Same applies to the Table. You created a Table instance and for each row you want to add to the table, you have to create a Row instance and populate it accordingly. Otherwise, your looping code is just updating the same row over and over again.

    For example:

    while (i < myDT.Rows.Count)
    {
        while (j < myDT.Columns.Count)
        {
            Row newRow = table.Rows.Add(20, Font.Helvetica, 12);
            newRow.Cells.Add(myDT.Rows[i][j].ToString());//need a default row here or way to add directly to the table
            j++;
        }
        j = 0;
        i++;
    }