This is a migrated thread and some comments may be shown as answers.

PrintExtensions with Large Amount of Data

3 Answers 148 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Mohamed Hussain Nabhan Hussain
Top achievements
Rank 1
Mohamed Hussain Nabhan Hussain asked on 05 Nov 2012, 11:12 AM

Kindly find the Below Code, this is the PrintExtensions Class that Prints an image of the Gridview data,
however on large amount of data, it takes maybe half an hour without doing anything and in the same time it consumes a lot of CPU memory.

but in small amount of data it works very fine. 
Any solution?

This is the Build of the rad controls I am using (RadControls for WPF, v.2012.2.1001.40)


Best Regards

public static class PrintExtensions
  
   {
  
       static FixedDocument ToFixedDocument(FrameworkElement element, PrintDialog dialog)
  
       {
  
  
  
           dialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
  
           PrintCapabilities capabilities = dialog.PrintQueue.GetPrintCapabilities(dialog.PrintTicket);
  
           Size pageSize = new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight);
  
           Size extentSize = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
  
           FixedDocument fixedDocument = new FixedDocument();
  
           element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
  
           element.Arrange(new Rect(new Point(0, 0), element.DesiredSize));
  
           for (double y = 0; y < element.DesiredSize.Height; y += extentSize.Height)
  
           {
  
               for (double x = 0; x < element.DesiredSize.Width; x += extentSize.Width)
  
               {
  
                   VisualBrush brush = new VisualBrush(element);
  
                   brush.Stretch = Stretch.None;
  
                   brush.AlignmentX = AlignmentX.Left;
  
                   brush.AlignmentY = AlignmentY.Top;
  
                   brush.ViewboxUnits = BrushMappingMode.Absolute;
  
                   brush.TileMode = TileMode.None;
  
                   brush.Viewbox = new Rect(x, y, extentSize.Width, extentSize.Height);
  
                   PageContent pageContent = new PageContent();
  
                   FixedPage page = new FixedPage();
  
                   ((IAddChild)pageContent).AddChild(page);
  
                   fixedDocument.Pages.Add(pageContent);
  
                   page.Width = pageSize.Width;
  
                   page.Height = pageSize.Height;
  
                   Canvas canvas = new Canvas();
  
                   FixedPage.SetLeft(canvas, capabilities.PageImageableArea.OriginWidth);
  
                   FixedPage.SetTop(canvas, capabilities.PageImageableArea.OriginHeight);
  
                   canvas.Width = extentSize.Width;
  
                   canvas.Height = extentSize.Height;
  
                   canvas.Background = brush;
  
                   page.Children.Add(canvas);
  
  
  
               }
  
  
  
           }
  
           return fixedDocument;
 
  
  
       }
  
  
  
       static GridViewDataControl ToPrintFriendlyGrid(GridViewDataControl source)
  
       {
  
           var grid = new RadGridView()
  
           {
  
               ItemsSource = source.ItemsSource,
  
               RowIndicatorVisibility = Visibility.Collapsed,
  
               ShowGroupPanel = false,
  
               CanUserFreezeColumns = false,
  
               IsFilteringAllowed = false,
  
               EnableColumnVirtualization=false,
  
               AutoExpandGroups = true,
  
               AutoGenerateColumns = false,
  
               Margin=new Thickness(10,30,10,10),
  
               ShowColumnFooters=true,
  
               EnableRowVirtualization=true
  
                 
  
                 
  
           };
  
           double widthsum = 0;
  
           foreach (var column in source.Columns.OfType<GridViewDataColumn>())
  
           {
  
               widthsum += column.Width.DisplayValue;
  
           }
  
           foreach (var column in source.Columns.OfType<GridViewDataColumn>())
  
           {
  
                 
  
               GridViewDataColumn newColumn = new GridViewDataColumn();
  
               newColumn.Width = column.ActualWidth;
  
               newColumn.DisplayIndex = column.DisplayIndex;
  
               //newColumn.DataMemberBinding = new System.Windows.Data.Binding(column.UniqueName);
 
               newColumn.DataMemberBinding = column.DataMemberBinding; // Better to just copy the references to get all the custom formatting
 
               newColumn.DataFormatString = column.DataFormatString;
  
               newColumn.TextAlignment = column.TextAlignment;
  
               newColumn.Header = column.Header;
  
               newColumn.Footer = column.Footer;
  
               newColumn.Width = 1030/ widthsum * column.Width.DisplayValue;
  
                 
  
               if (column.DataType.Name == "Decimal")
  
               {
  
                   //newColumn.TextAlignment = TextAlignment.Right;
  
                   SumFunction sum = new SumFunction { ResultFormatString = "Total : {0}", Caption = "" };
  
                   sum.ResultFormatString = "{0:n}";
  
                   newColumn.AggregateFunctions.Add(sum);
  
                   newColumn.FooterTextAlignment = TextAlignment.Right;
  
               }
  
               else
  
               {
  
                   newColumn.TextWrapping = TextWrapping.Wrap;
  
                     
  
               }
  
  
  
  
  
  
  
               grid.Columns.Add(newColumn);
  
           }
  
  
  
  
  
            
  
           StyleManager.SetTheme(grid, StyleManager.GetTheme(grid));
  
  
  
           grid.SortDescriptors.AddRange(source.SortDescriptors);
  
           grid.GroupDescriptors.AddRange(source.GroupDescriptors);
  
           grid.FilterDescriptors.AddRange(source.FilterDescriptors);
  
              
  
           return grid;
  
       }
  
  
  
       public enum ZoomType
  
       {
  
           Full,
  
           Width,
  
           Height,
  
           TwoWide
  
  
  
  
  
  
  
       };
  
  
  
  
  
       private static double constrain(double val, double val_min, double val_max)
  
       {
  
           if (val < val_min) return val_min;
  
           else if (val > val_max) return val_max;
  
           else return val;
  
       }
 
  
  
  
  
       public static void PrintPreview(this GridViewDataControl source,string title)
  
       {
  
  
  
           Window window = new Window();
  
           window.Title = "Print Preview";
  
           if (!string.IsNullOrWhiteSpace(source.ToolTip as string)) window.Title += " of " + source.ToolTip;
  
           window.Width = SystemParameters.PrimaryScreenWidth * 0.92;
  
           window.Height = SystemParameters.WorkArea.Height;
  
           window.Left = constrain(SystemParameters.VirtualScreenWidth - SystemParameters.PrimaryScreenWidth, 0, SystemParameters.VirtualScreenWidth - 11);
  
           window.Top = constrain(0, 0, SystemParameters.VirtualScreenHeight - 25);
  
           DocumentViewer viewer = new DocumentViewer();
  
           viewer.Document = ToFixedDocument(ToPrintFriendlyGrid(source), new PrintDialog());
  
           Zoom(viewer, ZoomType.Full);
  
           window.Content = viewer;
  
           window.Show();
  
  
  
       }
  
  
  
       public static void Zoom(DocumentViewer viewer, ZoomType zoom)
  
       {
  
           switch (zoom)
  
           {
  
               case ZoomType.Height: viewer.FitToHeight(); break;
  
               case ZoomType.Width: viewer.FitToWidth(); break;
  
               case ZoomType.TwoWide: viewer.FitToMaxPagesAcross(2); break;
  
               case ZoomType.Full: break;
  
           }
  
  
  
  
  
  
  
       }
 
  
  
       public static void Print(this GridViewDataControl source, bool showDialog, string title)
  
       {
  
           var dialog = new PrintDialog();
  
           var dialogResult = showDialog ? dialog.ShowDialog() : true;
  
  
  
           if (dialogResult == true)
  
           {
  
               var viewer = new DocumentViewer();
  
               Grid maingrid = new Grid();
  
               ColumnDefinition gridCol1 = new ColumnDefinition();
  
               maingrid.ColumnDefinitions.Add(gridCol1);
  
               RowDefinition gridRow1 = new RowDefinition();
  
               RowDefinition gridRow2 = new RowDefinition();
  
               maingrid.RowDefinitions.Add(gridRow1);
  
               maingrid.RowDefinitions.Add(gridRow2);
  
  
  
               TextBlock txtBlock1 = new TextBlock();
  
               txtBlock1.Text = title;
  
               txtBlock1.Margin = new Thickness(2, 2, 2, 2);
  
               txtBlock1.TextAlignment = TextAlignment.Center;
  
  
  
  
  
               Grid.SetRow(txtBlock1, 0);
  
               Grid.SetRow(ToPrintFriendlyGrid(source), 1);
  
               maingrid.Children.Add(txtBlock1);
  
               maingrid.Children.Add(ToPrintFriendlyGrid(source));
  
  
  
               viewer.Document = ToFixedDocument(maingrid, dialog);
  
               dialog.PrintDocument(viewer.Document.DocumentPaginator, "");
  
           }
  
       }
  
   }



3 Answers, 1 is accepted

Sort by
0
Dimitrina
Telerik team
answered on 05 Nov 2012, 11:55 AM
Hello,

From the code snippet you have provided I can see that you use PrintDocument. Unfortunately the UI components are not designed to work properly in print scenarios and after a lot of problems we abandoned this approach for printing.

I would suggest you to use the RadDocument and RadRichTextBox or Telerik Reporting instead. 

Greetings,
Didie
the Telerik team

Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

0
Mohamed Hussain Nabhan Hussain
Top achievements
Rank 1
answered on 07 Nov 2013, 09:10 AM
Thanks I ma Using now the RadDocument Solution, however when I print the Layout is somewhat strange and I couldn't fix it. I attached a File showing how the printing looks like.
1- The Group and The headers are not aligned with the datarow.
2-The Left and the Right space around the grid are not equal.

And Here is my Code
private RadDocument CreateDocumentReport(RadGridView grid, List<string> chosenColumns)
        {
            List<GridViewBoundColumnBase> columns = (from c in grid.Columns.OfType<GridViewBoundColumnBase>()
                                                     orderby c.DisplayIndex
                                                     select c).ToList();
 
            Telerik.Windows.Documents.Model.Table table = new Telerik.Windows.Documents.Model.Table();
 
            RadDocument document = new RadDocument();
            Telerik.Windows.Documents.Model.Section section = new Telerik.Windows.Documents.Model.Section();
            section.Blocks.Add(table);
            document.Sections.Add(section);
            section.PageOrientation = Telerik.Windows.Documents.Model.PageOrientation.Landscape;
            //section.PageMargin = new Documents.Layout.Padding(0, 50, 20, 0);
            section.ActualPageMargin = new Documents.Layout.Padding(1, 50, 20, 0);
            table.LayoutMode = Telerik.Windows.Documents.Model.TableLayoutMode.AutoFit;
              
            if (grid.ShowColumnHeaders)
            {
                AddHeaderRowReport(grid, columns, table, chosenColumns);
            }
 
            if (grid.Items.Groups != null)
            {
                for (int i = 0; i < grid.Items.Groups.Count; i++)
                {
                    AddGroupRowReport(table, grid.Items.Groups[i] as QueryableCollectionViewGroup, columns, grid, chosenColumns);
                    AddGroupFooterRow(grid,grid.Items.Groups[i] as QueryableCollectionViewGroup, grid.Columns, table, chosenColumns);
                }
            }
            else
            {
                AddDataRowsReport(table, grid.Items, columns, grid, chosenColumns);
            }
 
            if (grid.ShowColumnFooters)
            {
                AddFooterRow(grid, grid.Columns, table, chosenColumns);
            }
 
 
 
            return document;
        }
 
        private void AddHeaderRowReport(RadGridView grid, List<GridViewBoundColumnBase> columns, Telerik.Windows.Documents.Model.Table table, List<string> chosenColumns)
        {
            Telerik.Windows.Documents.Model.TableRow headerRow = new Telerik.Windows.Documents.Model.TableRow();
 
            if (grid.GroupDescriptors.Count > 0)
            {
                Telerik.Windows.Documents.Model.TableCell indentCell = new Telerik.Windows.Documents.Model.TableCell();
                indentCell.PreferredWidth = new TableWidthUnit(grid.GroupDescriptors.Count * 20);
                indentCell.Background = Colors.Black;
 
                headerRow.Cells.Add(indentCell);
            }
 
            for (int i = 0; i < columns.Count; i++)
            {
                if (chosenColumns.Any(itm => itm == columns[i].Header.ToString()))
                {
                    Telerik.Windows.Documents.Model.TableCell cell = new Telerik.Windows.Documents.Model.TableCell();
                    cell.Background = Colors.Black;
 
                    AddCellValueReportGroup(cell, columns[i].Header.ToString());
                    cell.PreferredWidth = new TableWidthUnit(200);
                    cell.VerticalAlignment = Documents.Layout.RadVerticalAlignment.Center;
                    TableCellBorders border = new TableCellBorders(BorderStyle.Single, Colors.Black);
                    cell.Borders = border;
 
                    headerRow.Cells.Add(cell);
                }
            }
            table.Rows.Add(headerRow);
        }
 
        private void AddFooterRow(RadGridView grid, Telerik.Windows.Controls.GridViewColumnCollection columns, Telerik.Windows.Documents.Model.Table table, List<string> chosenColumns)
        {
            Telerik.Windows.Documents.Model.TableRow footerRow = new Telerik.Windows.Documents.Model.TableRow();
 
            if (grid.GroupDescriptors.Count > 0)
            {
                Telerik.Windows.Documents.Model.TableCell indentCell = new Telerik.Windows.Documents.Model.TableCell();
                indentCell.PreferredWidth = new TableWidthUnit(grid.GroupDescriptors.Count * 20);
                indentCell.Background = Colors.LightBlue;
                footerRow.Cells.Add(indentCell);
            }
            
            for (int i = 0; i < columns.Count; i++)
            {
                if (chosenColumns.Any(itm => itm == columns[i].Header.ToString()))
                {
                    Telerik.Windows.Documents.Model.TableCell cell = new Telerik.Windows.Documents.Model.TableCell();
                    cell.Background = Colors.LightBlue;
                    float x;
                    object value = grid.AggregateResults[i].Value;
                    if (value != null)
                    {
                        value = float.TryParse(grid.AggregateResults[i].Value.ToString(), out x) ? grid.AggregateResults[i].Value.ToString() : string.Empty;
 
                    }
                    AddCellValueReport(cell, value != null ? value.ToString() : string.Empty);
                    cell.PreferredWidth = new TableWidthUnit(200);
                    cell.VerticalAlignment = Documents.Layout.RadVerticalAlignment.Center;
                    cell.TextAlignment = Documents.Layout.RadTextAlignment.Right;
                    TableCellBorders border = new TableCellBorders(BorderStyle.Single, Colors.Black);
                    cell.Borders = border;
                    footerRow.Cells.Add(cell);
                }
            }
 
            table.Rows.Add(footerRow);
        }
        private void AddGroupFooterRow(RadGridView grid,QueryableCollectionViewGroup group, Telerik.Windows.Controls.GridViewColumnCollection columns, Telerik.Windows.Documents.Model.Table table, List<string> chosenColumns)
        {
            Telerik.Windows.Documents.Model.TableRow footerRow = new Telerik.Windows.Documents.Model.TableRow();
 
            if (grid.GroupDescriptors.Count > 0)
            {
                Telerik.Windows.Documents.Model.TableCell indentCell = new Telerik.Windows.Documents.Model.TableCell();
                indentCell.PreferredWidth = new TableWidthUnit(grid.GroupDescriptors.Count * 20);
                indentCell.Background = Colors.LightBlue;
                footerRow.Cells.Add(indentCell);
            }
 
            for (int i = 0; i < columns.Count; i++)
            {
                if (chosenColumns.Any(itm => itm == columns[i].Header.ToString()))
                {
                    Telerik.Windows.Documents.Model.TableCell cell = new Telerik.Windows.Documents.Model.TableCell();
                    cell.Background = Colors.LightGray;
                    float x;
                    object value = group.AggregateResults[i].Value;
                    if (value != null)
                    {
                        value = float.TryParse(group.AggregateResults[i].Value.ToString(), out x) ? group.AggregateResults[i].Value.ToString() : string.Empty;
 
                    }
                    AddCellValueReport(cell, value != null ? value.ToString() : string.Empty);
                    cell.PreferredWidth = new TableWidthUnit(200);
                    cell.VerticalAlignment = Documents.Layout.RadVerticalAlignment.Center;
                    cell.TextAlignment = Documents.Layout.RadTextAlignment.Right;
                    TableCellBorders border = new TableCellBorders(BorderStyle.Single, Colors.Black);
                    cell.Borders = border;
                    footerRow.Cells.Add(cell);
                }
            }
 
            table.Rows.Add(footerRow);
        }
        private void AddDataRowsReport(Telerik.Windows.Documents.Model.Table table, IList items, IList<GridViewBoundColumnBase> columns, RadGridView grid, List<string> chosenColumns)
        {
            for (int i = 0; i < items.Count; i++)
            {
                Telerik.Windows.Documents.Model.TableRow row = new Telerik.Windows.Documents.Model.TableRow();
 
                if (grid.GroupDescriptors.Count > 0)
                {
                    Telerik.Windows.Documents.Model.TableCell indentCell = new Telerik.Windows.Documents.Model.TableCell();
                    indentCell.PreferredWidth = new TableWidthUnit(1);
                    indentCell.Background = RowBackground;
 
 
                    row.Cells.Add(indentCell);
                }
 
                for (int j = 0; j < columns.Count; j++)
                {
                    if (chosenColumns.Any(itm => itm == columns[j].Header.ToString()))
                    {
                        Telerik.Windows.Documents.Model.TableCell cell = new Telerik.Windows.Documents.Model.TableCell();
 
                        object value = columns[j].GetValueForItem(items[i]);
 
                        AddCellValueReport(cell, value != null ? value.ToString() : string.Empty);
 
                        cell.PreferredWidth = new TableWidthUnit(200);
                        cell.Background = RowBackground;
                        float x;
                        if (value != null)
                        {
                            cell.TextAlignment = float.TryParse(value.ToString(), out x) ? Documents.Layout.RadTextAlignment.Right : Documents.Layout.RadTextAlignment.Left;
 
                        }
                        TableCellBorders border = new TableCellBorders(BorderStyle.Single, Colors.Black);
                        cell.Borders = border;
                        row.Cells.Add(cell);
                    }
                }
 
                table.Rows.Add(row);
            }
        }
 
        private void AddGroupRowReport(Telerik.Windows.Documents.Model.Table table, QueryableCollectionViewGroup group, IList<GridViewBoundColumnBase> columns, RadGridView grid, List<string> chosenColumns)
        {
            Telerik.Windows.Documents.Model.TableRow row = new Telerik.Windows.Documents.Model.TableRow();
 
            int level = GetGroupLevel(group);
            if (level > 0)
            {
                Telerik.Windows.Documents.Model.TableCell cell = new Telerik.Windows.Documents.Model.TableCell();
                cell.PreferredWidth = new TableWidthUnit(level * 20);
                cell.Background = GroupHeaderBackground;
                row.Cells.Add(cell);
            }
 
            Telerik.Windows.Documents.Model.TableCell aggregatesCell = new Telerik.Windows.Documents.Model.TableCell();
            aggregatesCell.Background = GroupHeaderBackground;
            aggregatesCell.ColumnSpan = chosenColumns.Count + (grid.GroupDescriptors.Count > 0 ? 1 : 0) - (level > 0 ? 1 : 0);
            AddCellValueReportGroupHeader(aggregatesCell, group.Key != null ? group.Key.ToString() : string.Empty);
            TableCellBorders border = new TableCellBorders(BorderStyle.Single, Colors.Black);
            aggregatesCell.Borders = border;
            //aggregatesCell.Padding = new Documents.Layout.Padding(20, 0, 0, 0);
            //foreach (AggregateResult result in group.AggregateResults)
            //{
            //    AddCellValueReportGroup(aggregatesCell, result.FormattedValue != null ? result.FormattedValue.ToString() : string.Empty);
            //}
 
            row.Cells.Add(aggregatesCell);
 
            table.Rows.Add(row);
 
            if (group.HasSubgroups)
            {
                foreach (var g in group.Subgroups)
                {
                    AddGroupRowReport(table, g as QueryableCollectionViewGroup, columns, grid, chosenColumns);
                }
            }
            else
            {
                AddDataRowsReport(table, group.Items, columns, grid, chosenColumns);
            }
        }
 
        private void AddCellValueReport(Telerik.Windows.Documents.Model.TableCell cell, string value)
        {
            Telerik.Windows.Documents.Model.Paragraph paragraph = new Telerik.Windows.Documents.Model.Paragraph();
            cell.Blocks.Add(paragraph);
              
            Telerik.Windows.Documents.Model.Span span = new Telerik.Windows.Documents.Model.Span();
 
            span.Text = value == "" ? " " : value;
            span.FontSize = 9;
            
            paragraph.Inlines.Add(span);
        }
 
        private void AddCellValueReportGroupHeader(Telerik.Windows.Documents.Model.TableCell cell, string value)
        {
            Telerik.Windows.Documents.Model.Paragraph paragraph = new Telerik.Windows.Documents.Model.Paragraph();
            cell.Blocks.Add(paragraph);
            cell.Padding = new Documents.Layout.Padding(20, 0, 0, 0);
            Telerik.Windows.Documents.Model.Span span = new Telerik.Windows.Documents.Model.Span();
 
            span.Text = value == "" ? " " : value;
            span.FontSize = 9;
 
            paragraph.Inlines.Add(span);
        }
 
        private void AddCellValueReportGroup(Telerik.Windows.Documents.Model.TableCell cell, string value)
        {
            Telerik.Windows.Documents.Model.Paragraph paragraph = new Telerik.Windows.Documents.Model.Paragraph();
            cell.Blocks.Add(paragraph);
 
            Telerik.Windows.Documents.Model.Span span = new Telerik.Windows.Documents.Model.Span();
 
            span.Text = value == "" ? " " : value;
            span.FontSize = 9;
            span.ForeColor = Colors.White;
            paragraph.Inlines.Add(span);
        }
 
 
 
 
 
 
 
 
        private int GetGroupLevel(IGroup group)
        {
            int level = 0;
 
            IGroup parent = group.ParentGroup;
 
            while (parent != null)
            {
                level++;
                parent = parent.ParentGroup;
            }
 
            return level;
        }
0
Dimitrina
Telerik team
answered on 12 Nov 2013, 08:04 AM
Hello,

I have attached a document with some guidance on how to create the RadDocument and align its elements properly. You can also check this help article on creating a document table in code behind. 

I hope this helps.

Regards,
Didie
Telerik
TRY TELERIK'S NEWEST PRODUCT - EQATEC APPLICATION ANALYTICS for WPF.
Learn what features your users use (or don't use) in your application. Know your audience. Target it better. Develop wisely.
Sign up for Free application insights >>
Tags
GridView
Asked by
Mohamed Hussain Nabhan Hussain
Top achievements
Rank 1
Answers by
Dimitrina
Telerik team
Mohamed Hussain Nabhan Hussain
Top achievements
Rank 1
Share this question
or