Search code examples
c#flowdocument

DataTable in FlowDocument


I am trying to create a flowdocument with a Table of data which I want to print on the printer. I can create the flowdocument and the printer stuff, but I don't know how to create the table.

Here is my code:

        //Creating flow document
        Paragraph myParagraph = new Paragraph();

        //Add content to the paragraph
        myParagraph.Inlines.Add(new Bold(new Run("List of tasks (" + TasksToShow.Count + ")")));

        //Create content of paragraph
        DataTable myTable = new DataTable();
        myTable.Columns.Add("Task ID", typeof(int));
        myTable.Columns.Add("Task name", typeof(string));

        foreach (Task task in TasksToShow)
        {
            myTable.Rows.Add(task.TaskID, task.TaskName);
        }

        //Adding content to the flow document
        FlowDocument myFlowDocument = new FlowDocument();
        myFlowDocument.Blocks.Add(myParagraph);
        myFlowDocument.Blocks.Add(myTable);               //This line fails :(

        //Print the document
        PrintDialog dialog = new PrintDialog();
        if(dialog.ShowDialog() == true)
        {
            int margin = 5;
            Size pageSize = new Size(dialog.PrintableAreaWidth - margin * 2, dialog.PrintableAreaHeight - margin * 2);
            IDocumentPaginatorSource paginator = myFlowDocument;
            paginator.DocumentPaginator.PageSize = pageSize;
            dialog.PrintDocument(paginator.DocumentPaginator, "Flow print"); 
        }

Solution

  • you can do like this.....

    // Create the parent FlowDocument...
    flowDoc = new FlowDocument();
    
    // Create the Table...
    table1 = new Table();
    // ...and add it to the FlowDocument Blocks collection.
    flowDoc.Blocks.Add(table1);
    
    
    // Set some global formatting properties for the table.
    table1.CellSpacing = 10;
    table1.Background = Brushes.White;
    

    pls go through this links for more info

    after that you can change this depnds upon the your requirement...