Printing in WinUI DataGrid

3 May 202120 minutes to read

DataGrid provides support to print the data displayed in the DataGrid using SfDataGrid.Print method.

this.sfDataGrid.Print();

SfDataGrid provides various options to customize print preview settings using SfDataGrid.PrintSettings property of type DataGridPrintSettings.

sfDataGrid.PrintSettings.CanRepeatHeaders = true;
sfDataGrid.Print();

Print

Print method opens the print dialog where user can select the available printer, change the orientation and preview of the DataGrid to be printed will be loaded on print preview panel.

Printing in WinUI DataGrid

Scaling

SfDataGrid provides support to scale rows or columns or both while printing to fit on one page. Scaling options can be changed by setting PrintSettings.ScalingOption property.

sfDataGrid.PrintSettings.ScalingOption = PrintScalingOptions.FitAllColumnsOnOnePage;
sfDataGrid.Print();

Column Header on each page

Column headers can be printed on each page by enabling PrintSettings.CanRepeatHeaders property while printing.

sfDataGrid.PrintSettings.CanRepeatHeaders = true;
sfDataGrid.Print();

Changing Flow Direction while printing

You can change the text direction in print page by using PrintSettings.FlowDirection property.

sfDataGrid.PrintSettings.FlowDirection = FlowDirection.RightToLeft;
sfDataGrid.Print();

SfDataGrid provides support to print the StackedHeaders by setting the PrintSettings.CanPrintStackedHeaders as ‘true’.

sfDataGrid.PrintSettings.CanPrintStackedHeaders = true;
sfDataGrid.Print();

WinUI DataGrid displays Printing with Stacked Headers

Page Settings

SfDataGrid provides various options to customize page settings using SfDataGrid.PrintSettings property of type DataGridPrintSettings.

Orientation

SfDataGrid provides support to switch between Portrait (more rows but fewer columns) and Landscape (more columns but fewer rows) orientation while printing. Orientation can be changed by setting PrintSettings.Orientation Property.
Orientation can also be changed in print dialog at runtime by selecting a option from orientation drop-down.

sfDataGrid.PrintSettings.Orientation = PrintOrientation.Landscape;
sfDataGrid.Print();

Page size

SfDataGrid provides support to change the page size. Page size can be changed by setting PrintSettings.PageSize property.

sfDataGrid.PrintSettings.PageSize = new Size(800, 800);
sfDataGrid.Print();

Page padding

SfDataGrid provides support to change the page padding to adjust content in printed page. Page padding can be changed by setting PrintSettings.PagePadding property.

sfDataGrid.PrintSettings.PagePadding = ThicknessHelper.FromLengths(10, 20, 10, 20);
sfDataGrid.Print();

SfDataGrid provides a way to display additional content at the top (Header) or bottom (Footer) of the page while printing. This can be achieved by setting PageHeaderHeight, HeaderTemplate, FooterHeight, FooterTemplate properties in PrintSettings.

Steps to add page header while printing,

1.Create DataTemplate in Page.Resources.

<Page.Resources>
    <DataTemplate x:Key="PageHeaderTemplate">
        <Grid Background="Gray">
            <TextBlock Text="Syncfusion" FontSize="18" FontWeight="Bold" 
            Foreground="White" HorizontalAlignment="Center"/>
        </Grid>
    </DataTemplate>
</Page.Resources>

2.Set the above defined DataTemplate to PrintSettings.HeaderTemplate and assign value for PrintSettings.PageHeaderHeight property also.

sfDataGrid.PrintSettings.PageHeaderHeight = 30;
sfDataGrid.PrintSettings.HeaderTemplate = Resources["PageHeaderTemplate"] as DataTemplate;
sfDataGrid.Print();

3.Now run the application and you can see page header in all the pages. In the same way, you can set PrintSettings.FooterTemplate also.

Customized Header Height in WinUI DataGrid Printing

NOTE

DataGridPrintManager is the DataContext for DataGridPrintPageControl, where the header and footer templates are loaded.

Printing Current Date time

You can print current Date and Time at each page by setting the FooterHeight, FooterTemplate properties in PrintSettings.

<Page.Resources>        
    <local:OrderInfoViewModel  x:Key="viewModel"/>    
    <DataTemplate x:Key="PageFooterTemplate">
        <Grid>
            <TextBlock HorizontalAlignment="Center" FontSize="20" VerticalAlignment="Center"  
             Text="{Binding Path=Date, Source={StaticResource viewModel}}"/>
        </Grid>
    </DataTemplate>
</Page.Resources>
sfDataGrid.PrintSettings.FooterHeight = 30;
sfDataGrid.PrintSettings.FooterTemplate = Resources["PageFooterTemplate"] as DataTemplate;
sfDataGrid.Print();

WinUI DataGrid displays Current DateTime in Printing

Printing with styles

When you want to print the SfDataGrid with same appearance settings as in the display (Background and Foreground) or with custom appearance by writing styles.
You can print SfDataGrid as it displayed in View by setting PrintSettings.CanPrintStyles to true.

sfDataGrid.PrintSettings.CanPrintStyles = true;
sfDataGrid.Print();

GridHeaderCellControl style customized and the same style will be exported while printing by setting PrintSettings.CanPrintStyles to true.

<Page.Resources>
    <Style TargetType="dataGrid:GridHeaderCellControl">
        <Setter Property="Background" Value="LightPink"/>
    </Style>
</Page.Resources>

WinUI DataGrid Printing with Styling

Printing Customization

Printing operations can be customized by overriding DataGridPrintManager and its available methods.

Setting different row height

SfDataGrid allows you to set different row height for specific rows while printing. You can achieve this by overriding the GetRowHeight method in DataGridPrintManager class.

public class CustomPrintManager : DataGridPrintManager
{
    public CustomPrintManager(SfDataGrid grid)
        : base(grid)
    {
    }

    protected override double GetRowHeight(object record, int rowIndex, RowType type)
    {
        if (rowIndex != -1 && !(record is Group) && rowIndex % 2 != 0)
            return 80.0;
        return base.GetRowHeight(record, rowIndex, type);
    }
}
sfDataGrid.PrintSettings.PrintManager = new CustomPrintManager(this.sfDataGrid);
sfDataGrid.PrintSettings.PrintManager.Print();

Customized Row Height in WinUI DataGrid Printing

Hiding rows while printing

You can hide specific row by using GetRowHeight method in DataGridPrintManager class and setting height as 0.
Here, unbound row is excluded while printing. Likewise, you can hide any row based on record and row index.

public class CustomPrintManager : DataGridPrintManager
{
    public CustomPrintManager(SfDataGrid grid)
        : base(grid)
    {
    }

    protected override double GetRowHeight(object record, int rowIndex, RowType type)
    {
        if (record is GridUnboundRow)
           return 0;
        return base.GetRowHeight(record, rowIndex, type);
    }
}
sfDataGrid.PrintSettings.PrintManager = new CustomPrintManager(this.sfDataGrid);
sfDataGrid.PrintSettings.PrintManager.Print();

Setup columns to be printed

SfDataGrid allows you to the exclude the columns while printing the grid. You can change the column list by overriding the GetColumns method in DataGridPrintManager class.

public class CustomPrintManager : DataGridPrintManager
{
    public CustomPrintManager(SfDataGrid grid)
        : base(grid)
    {
    }

    protected override List<GridColumn> GetColumns()
    {
        List<GridColumn> columns = new List<GridColumn>();
        columns = dataGrid.Columns.ToList();
        columns.Remove(columns.FirstOrDefault(x => x.MappingName == "OrderDate"));
        return columns;
    }
}
sfDataGrid.PrintSettings.PrintManager = new CustomPrintManager(this.sfDataGrid);
sfDataGrid.PrintSettings.PrintManager.Print();

WinUI DataGrid Printing with Hidden Column

Customize the header text while printing

SfDataGrid allows you to change column header text while printing the grid. You can change the Column header text by overriding the GetColumnHeaderText method in DataGridPrintManager.

public class CustomPrintManager : DataGridPrintManager
{
    public CustomPrintManager(SfDataGrid grid)
        : base(grid)
    {
    }

    protected override string GetColumnHeaderText(string mappingName)
    {
        if (mappingName == "UnitPrice")
            return "Price Per Unit";
        return base.GetColumnHeaderText(mappingName);
    }

}
sfDataGrid.PrintSettings.PrintManager = new CustomPrintManager(this.sfDataGrid);
sfDataGrid.PrintSettings.PrintManager.Print();

Customized Header Text in WinUI DataGrid Printing

Styling Rows

You can apply row styles based on custom logic by overriding GetPrintGridCell method in DataGridPrintManager.

public class CustomPrintManager : DataGridPrintManager
{
    public CustomPrintManager(SfDataGrid grid)
        : base(grid)
    {
    }

    protected override ContentControl GetPrintGridCell(object data, GridColumn column)
    {
        if (!(data is OrderInfo))
            return base.GetPrintGridCell(data, column);

        if ((data as OrderInfo).OrderID == 10001)
            return new PrintGridCell() { Background = new SolidColorBrush(Colors.Bisque) };

        else if ((data as OrderInfo).OrderID == 10005)
            return new PrintGridCell() { Background = new SolidColorBrush(Colors.LightSkyBlue) };
        return base.GetPrintGridCell(data, column);
    }
}
sfDataGrid.PrintSettings.PrintManager = new CustomPrintManager(this.sfDataGrid);
sfDataGrid.PrintSettings.PrintManager.Print();
Appearance to be customized Method
Header Cell

GetPrintHeaderCell

Normal Cells

GetPrintGridCell

Caption summary cells

GetPrintCaptionSummaryCell

Group summary cells

GetPrintGroupSummaryCell

Table summary cells

GetPrintTableSummaryCell

Unbound row cells

GetPrintUnboundRowCell

Customizing Row Style in WinUI DataGrid Printing

Setup alternate row style

SfDataGrid allows you to apply alternative row style by overriding GetPrintGridCell method in DataGridPrintManager.

public class CustomPrintManager : DataGridPrintManager
{
    public CustomPrintManager(SfDataGrid grid)
        : base(grid)
    {
    }

    protected override ContentControl GetPrintGridCell(object data, GridColumn column)
    {
        var index = dataGrid.View.Records.IndexOfRecord(data);

        if (index % 2 == 0)
            return new PrintGridCell() { Background = new SolidColorBrush(Colors.Bisque) };
        return base.GetPrintGridCell(data, column);
    }
}
sfDataGrid.PrintSettings.PrintManager = new CustomPrintManager(this.sfDataGrid);
sfDataGrid.PrintSettings.PrintManager.Print();

Customizing Alternative Row Style in WinUI DataGrid Printing

Styling Columns

You can apply column styles based on custom logic by overriding GetPrintGridCell method in DataGridPrintManager.

public class CustomPrintManager : DataGridPrintManager
{
    public CustomPrintManager(SfDataGrid grid)
        : base(grid)
    {
    }

    protected override ContentControl GetPrintGridCell(object data, GridColumn column)
    {
        if (column.MappingName == "OrderID")
            return new PrintGridCell() { Background = new SolidColorBrush(Colors.LightGreen), FontStyle = Windows.UI.Text.FontStyle.Italic };
        return base.GetPrintGridCell(data, column);
    }
}
sfDataGrid.PrintSettings.PrintManager = new CustomPrintManager(this.sfDataGrid);
sfDataGrid.PrintSettings.PrintManager.Print();

Customizing Column in WinUI DataGrid Printing

NOTE

GetColumnWidth, GetColumnTextWrapping and GetColumnTextAlignment methods are also used for column customization while printing.

Printing selected rows

Selected rows can be printed by overriding GetSourceListForPrinting method in DataGridPrintManager class.

public class CustomPrintManager : DataGridPrintManager
{
    public CustomPrintManager(SfDataGrid grid)
        : base(grid)
    {
    }

    protected override IList GetSourceListForPrinting()
    {
        List<object> selectedRecords = new List<object>();
        var selectedRows = dataGrid.SelectionController.SelectedRows.ToList();

        foreach (var row in selectedRows)
        {

            if (row.IsAddNewRow || (row.NodeEntry != null && (!row.NodeEntry.IsRecords)))
                continue;

            if (row.IsUnboundRow)
            {
                var _row = dataGrid.UnboundRows.FirstOrDefault(r => r.Position == row.GridUnboundRowInfo.Position && r.ShowBelowSummary == row.GridUnboundRowInfo.ShowBelowSummary && r.RowIndex == row.GridUnboundRowInfo.RowIndex);
                selectedRecords.Add(_row);
            }

            else
                selectedRecords.Add(row.NodeEntry);
        }
        return selectedRecords;
    }
}
sfDataGrid.PrintSettings.PrintManager = new CustomPrintManager(this.sfDataGrid);
sfDataGrid.PrintSettings.PrintManager.Print();

Printing Selected Rows in WinUI DataGrid

Printing specific pages

The specific pages can be printed by customizing the print preview window to have options for custom page range through events and customizing the default print manager.

Add custom page range option

You can print the range of pages by adding the CustomPageRanges option to the PrintTaskOptions.DisplayedOptions property and also add all other available options in the StandardPrintTaskOptions and do the customization to support all other options in SfDataGrid.PrintTaskRequested event.
You have to call the PrintTaskRequest.CreatePrintTask method using DataGridPrintTaskRequested.Request property. While performing the custom operation in this event, you have to set the DataGridPrintTaskRequestedEventArgs.PrintDocumentSource property in PrintTaskSourceRequestedArgs.SetSource which is the event args for event handler available in PrintTaskRequest.CreatePrintTask method.

In the below code, print task has been created with changing needed PageRangeOptions.

sfDataGrid.PrintTaskRequested += DataGrid_PrintTaskRequested;

private void DataGrid_PrintTaskRequested(object sender, DataGridPrintTaskRequestedEventArgs e)
{
    e.PrintTask = e.Request.CreatePrintTask("Printing", sourceRequested =>
    {

        PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(e.PrintTask.Options);
        IList<string> displayedOptions = printDetailedOptions.DisplayedOptions;
        displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.CustomPageRanges);
        e.PrintTask.Options.PageRangeOptions.AllowCurrentPage = true;
        e.PrintTask.Options.PageRangeOptions.AllowAllPages = true;
        e.PrintTask.Options.PageRangeOptions.AllowCustomSetOfPages = true;

        sourceRequested.SetSource(e.PrintDocumentSource);

    });    
}

Printing Specific Pages in WinUI DataGrid

NOTE

View sample in GitHub.

Disable print preview

You can disable the print preview in print dialog by setting PrintTask.IsPreviewEnabled property to false.

sfDataGrid.PrintTaskRequested += DataGrid_PrintTaskRequested;

private void DataGrid_PrintTaskRequested(object sender, DataGridPrintTaskRequestedEventArgs e)
{
    e.PrintTask = e.Request.CreatePrintTask("Printing", sourceRequested =>
    {       
        sourceRequested.SetSource(e.PrintDocumentSource);
    }); 
	e.PrintTask.IsPreviewEnabled = false;
}

WinUI DataGrid displays Disabled Print Preview

NOTE

View sample in GitHub.