Printing in UWP DataGrid (SfDataGrid)
10 May 202124 minutes to read
SfDataGrid provides support to print the data displayed in the DataGrid using SfDataGrid.Print method.
dataGrid.Print();
Print Settings
SfDataGrid provides various options to customize print preview settings using SfDataGrid.PrintSettings property of type PrintSettings.
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.AllowRepeatHeaders = false;
dataGrid.Print();
Print method opens the System print dialog where user can select the printer and set the number of copies to be printed.
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.PrintScaleOption property.
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.AllowColumnWidthFitToPrintPage = false;
dataGrid.PrintSettings.PrintScaleOption = PrintScaleOptions.FitAllColumnsonOnePage;
dataGrid.Print();
Column Header on each page
Column headers can be printed on each page by enabling PrintSettings.AllowRepeatHeaders property while printing.
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.AllowRepeatHeaders = true;
dataGrid.Print();
Changing Flow Direction while printing
You can change the text direction in print page by using PrintSettings.PrintFlowDirection property.
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.PrintFlowDirection = FlowDirection.RightToLeft;
dataGrid.Print();
Print with StackedHeaders
SfDataGrid provides support to print the StackedHeaders by setting the PrintSettings.CanPrintStackedHeaders as ‘true’.
this.sfDataGrid.PrintSettings.CanPrintStackedHeaders = true;
Page Settings
SfDataGrid provides various options to customize page settings using SfDataGrid.PrintSettings property of type PrintSettings.
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.PrintPageOrientation Property.
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.PrintPageOrientation = PrintOrientation.Landscape;
dataGrid.Print();
Page size
SfDataGrid provides support to change the page size. Page size can be changed by setting PrintSettings.PrintPageWidth and PrintSettings.PrintPageHeight properties.
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.PrintPageHeight = 800;
dataGrid.PrintSettings.PrintPageWidth = 800;
dataGrid.Print();
Page margin
SfDataGrid provides support to change the page margins to adjust content in printed page. Page margin can be changed by setting PrintSettings.PrintPageMargin property.
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.PrintPageMargin = new Thickness(5);
dataGrid.Print();
Setting Header and Footer
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 PrintPageHeaderHeight, PrintPageHeaderTemplate, PrintPageFooterHeight, PrintPageFooterTemplate properties in PrintSettings.
Steps to add page header while printing,
- Create DataTemplate in Application.Resources.
<Application.Resources>
<DataTemplate x:Key="PageHeaderTempalte">
<Grid Background="Gray">
<TextBlock Text="Syncfusion" FontSize="18" FontWeight="Bold"
Foreground="White" HorizontalAlignment="Center"/>
</Grid>
</DataTemplate>
</Application.Resources>
- Set the above defined DataTemplate to PrintSettings.PrintPageHeaderTemplate and assign value for PrintSettings.PrintPageHeaderHeight property also.
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.PrintPageHeaderHeight = 30;
dataGrid.PrintSettings.PrintPageHeaderTemplate = Application.Current.Resources["PageHeaderTempalte"] as DataTemplate;
dataGrid.Print();
3.Now run the application and you can see page header in all the pages. In the same way, you can set PrintSettings.PrintPageFooterTemplate also.
NOTE
PrintManagerBase is the DataContext for PrintPageControl, 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 PrintPageFooterHeight, PrintPageFooterTemplate properties in PrintSettings.
<Page.Resources>
<local:ViewModel x:Key="viewModel"/>
<DataTemplate x:Key="PageFooterTempalte">
<Grid>
<TextBlock HorizontalAlignment="Center" FontSize="20" VerticalAlignment="Center"
Text="{Binding Path=Date, Source={StaticResource viewModel}}"/>
</Grid>
</DataTemplate>
</Page.Resources>
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.PrintPageFooterHeight = 30;
dataGrid.PrintSettings.PrintPageFooterTemplate = Resources["PageFooterTempalte"] as DataTemplate;
dataGrid.Print();
Printing using UIElement Rendering
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.AllowPrintStyles to true.
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.AllowPrintStyles = true;
dataGrid.Print();
GridHeaderCellControl style customized and the same style will be exported while printing by setting PrintSettings.AllowPrintStyles to true.
<Application.Resources>
<Style TargetType="syncfusion:GridHeaderCellControl">
<Setter Property="Background" Value="LightPink"/>
</Style>
</Application.Resources>
Applying custom style
Custom styles can be applied while printing by setting PrintSettings.AllowPrintStyles to false and writing style for below controls based on your requirement.
Appearance to be customized | TargetType of Style |
---|---|
Header Cell | |
Normal Cells | |
Caption summary cells | |
Group summary cells | |
Table summary cells | |
Unbound row cells |
To provide custom appearance for Header cells while printing, PrintHeaderCell style is customized.
<Application.Resources>
<Style TargetType="syncfusion:PrintHeaderCell">
<Setter Property="Background" Value="LightSkyBlue"/>
</Style>
</Application.Resources>
To print SfDataGrid with custom styles, PrintSettings.AllowPrintStyles property to false.
dataGrid.PrintSettings = new PrintSettings();
dataGrid.PrintSettings.AllowPrintStyles = false;
dataGrid.Print();
Printing Customization
Printing operations can be customized by overriding GridPrintManager 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 PrintManagerBase class.
public class CustomPrintManager : GridPrintManager
{
public CustomPrintManager(SfDataGrid grid)
: base(grid)
{
}
protected override double GetRowHeight(object record, int rowIndex, RowType type)
{
if (rowIndex != -1 && !(record is Group))
if (rowIndex % 2 != 0)
return 80.0;
return base.GetRowHeight(record, rowIndex, type);
}
}
dataGrid.PrintSettings.PrintManagerBase = new CustomPrintManager(this.dataGrid);
dataGrid.PrintSettings.PrintManagerBase.Print();
Hiding rows while printing
You can hide specific row by using GetRowHeight method in PrintManagerBase 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 : GridPrintManager
{
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);
}
}
dataGrid.PrintSettings.PrintManagerBase = new CustomPrintManager(this.dataGrid);
dataGrid.PrintSettings.PrintManagerBase.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 GetColumnNames method in PrintManagerBase class.
public class CustomPrintManager : GridPrintManager
{
public CustomPrintManager(SfDataGrid grid)
: base(grid)
{
}
protected override List<string> GetColumnNames()
{
List<string> columnList = this.dataGrid.Columns.
Select(x => x.MappingName).ToList();
columnList.Remove("CustomerName");
return columnList;
}
}
dataGrid.PrintSettings.PrintManagerBase = new CustomPrintManager(this.dataGrid);
dataGrid.PrintSettings.PrintManagerBase.Print();
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 GridPrintManager.
public class CustomPrintManager : GridPrintManager
{
public CustomPrintManager(SfDataGrid grid)
: base(grid)
{
}
protected override string GetColumnHeaderText(string mappingName)
{
if (mappingName == "OrderID")
return "Order ID";
return base.GetColumnHeaderText(mappingName);
}
}
dataGrid.PrintSettings.PrintManagerBase = new CustomPrintManager(this.dataGrid);
dataGrid.PrintSettings.PrintManagerBase.Print();
Styling Rows
You can apply row styles based on custom logic by overriding GetPrintGridCell method in GridPrintManager.
public class CustomPrintManager : GridPrintManager
{
public CustomPrintManager(SfDataGrid grid)
: base(grid)
{
}
public override ContentControl GetPrintGridCell(object record, string mappingName)
{
if (!(record is OrderInfo))
return base.GetPrintGridCell(record, mappingName);
if ((record as OrderInfo).Country == "Germany")
return new PrintGridCell() { Background = new SolidColorBrush(Colors.Bisque) };
else if ((record as OrderInfo).Country == "Mexico")
return new PrintGridCell() { Background = new SolidColorBrush(Colors.LightSkyBlue) };
return base.GetPrintGridCell(record, mappingName);
}
}
dataGrid.PrintSettings.PrintManagerBase = new CustomPrintManager(this.dataGrid);
dataGrid.PrintSettings.PrintManagerBase.Print();
Appearance to be customized | Method |
---|---|
Header Cell | |
Normal Cells | |
Caption summary cells | |
Group summary cells | |
Table summary cells | |
Unbound row cells |
Setup alternate row style
SfDataGrid allows you to apply alternative row style by overriding GetPrintGridCell method in GridPrintManager
.
public class CustomPrintManager : GridPrintManager
{
public CustomPrintManager(SfDataGrid grid)
: base(grid)
{
}
public override ContentControl GetPrintGridCell(object record, string mappingName)
{
var index = dataGrid.View.Records.IndexOfRecord(record);
if (index % 2 == 0)
return new PrintGridCell() { Background = new SolidColorBrush(Colors.Bisque) };
return base.GetPrintGridCell(record, mappingName);
}
}
dataGrid.PrintSettings.PrintManagerBase = new CustomPrintManager(this.dataGrid);
dataGrid.PrintSettings.PrintManagerBase.Print();
Styling Columns
You can apply column styles based on custom logic by overriding GetPrintGridCell method in GridPrintManager
.
public class CustomPrintManager : GridPrintManager
{
public CustomPrintManager(SfDataGrid grid)
: base(grid)
{
}
public override ContentControl GetPrintGridCell(object record, string mappingName)
{
if (mappingName == "OrderID")
return new PrintGridCell() { Background = new SolidColorBrush(Colors.LightGreen), FontStyle = Windows.UI.Text.FontStyle.Italic };
return base.GetPrintGridCell(record, mappingName);
}
}
dataGrid.PrintSettings.PrintManagerBase = new CustomPrintManager(this.dataGrid);
dataGrid.PrintSettings.PrintManagerBase.Print();
NOTE
GetColumnWidth, GetColumnTextWrapping, GetColumnTextAlignment and GetColumnPadding methods are also used for column customization while printing.
Printing Selected rows
Selected rows can be printed by overriding GetSourceListForPrinting method in PrintManagerClass
class.
public class CustomPrintManager : GridPrintManager
{
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;
}
}
dataGrid.PrintSettings.PrintManagerBase = new CustomPrintManager(this.dataGrid);
dataGrid.PrintSettings.PrintManagerBase.Print();
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, to add the page range options in print dialog.
this.dataGrid.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);
});
}
Customize print manager to print specific pages
You can print the specific pages by overriding OnAddPrintPages method in PrintManagerBase
class.
public class CustomPrintManager : GridPrintManager
{
public CustomPrintManager(SfDataGrid grid)
: base(grid)
{
}
protected override void OnAddPrintPages(AddPagesEventArgs e)
{
IList<Windows.Graphics.Printing.PrintPageRange> customPageRanges = e.PrintTaskOptions.CustomPageRanges;
int pageCount = this.PageDictionary.Count;
// An empty CustomPageRanges means "All Pages"
if (customPageRanges.Count == 0)
{
// Loop over all of the preview pages and add each one to be printed
for (var i = 1; i <= pageCount; i++)
{
var printpageControl = CreatePage(i);
PrintDocument.AddPage(printpageControl);
}
}
else
{
// Print only the pages chosen by the user.
//
// The "Current page" option is a special case of "Custom set of pages".
// In case the user selects the "Current page" option, the PrintDialog
// will turn that into a CustomPageRanges containing the page that the user was looking at.
// If the user typed in an indefinite range such as "6-", the LastPageNumber value
// will be whatever this sample app last passed into the PrintDocument.SetPreviewPageCount API.
foreach (PrintPageRange pageRange in customPageRanges)
{
// The user may type in a page number that is not present in the document.
// In this case, we just ignore those pages, hence the checks
// (pageRange.FirstPageNumber <= printPreviewPages.Count) and (i <= printPreviewPages.Count).
//
// If the user types the same page multiple times, it will be printed multiple times
// (e.g 3-4;1;1 will print pages 3 and 4 followed by two copies of page 1)
if (pageRange.FirstPageNumber <= pageCount)
{
for (int i = pageRange.FirstPageNumber; (i <= pageRange.LastPageNumber) && (i <= pageCount); i++)
{
// Subtract 1 because page numbers are 1-based, but our list is 0-based.
var printpageControl = CreatePage(i);
PrintDocument.AddPage(printpageControl);
}
}
}
}
// Indicate that all of the print pages have been provided.
PrintDocument.AddPagesComplete();
}
}
dataGrid.PrintSettings.PrintManagerBase = new CustomPrintManager(this.dataGrid);
dataGrid.PrintSettings.PrintManagerBase.Print();
NOTE
View sample in GitHub.
NOTE
Printing the specific pages in uwp datagrid support only for the uwp target build version as 17763 or above. For more information click here.
Disable print preview
You can disable the print preview in print dialog by setting PrintTask.IsPreviewEnabled property to false.
this.dataGrid.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;
}
NOTE
View sample in GitHub.