RadGridView Print and Print Preview

38 posts, 1 answers
  1. Answer
    Womack
    Womack avatar
    1 posts
    Member since:
    Dec 2009

    Posted 25 May 2010 Link to this post

    NOTE: This approach is not supported any more. Unfortunately the UI components are not designed to work properly in print/print preview scenarios. Please check the project attached in the end of the thread or our online demos and documentation for most recent examples.

    Requirements

    RadControls version

     

    WPF Q1 2010 SP1
    .NET version

     

    4.0
    Visual Studio version

     

    2010
    programming language

     

    C#

    PROJECT DESCRIPTION
    I recently wanted to enable my GridView to perform print and print preview functions.  The example at Vladimir Enchev's Post about Print Preview was a great start, but it had the following limitations:
    • It only showed the first page of a multi-page (too wide and too high to fit on one page) grid
    • It did not support adding a custom title (I've done this through the Grid.ToolTip property)
    • It did not open up to a reasonable size (I detect multiple monitors and open it in most of the second)
    • It did not provide arguments for Portrait vs. Landscape
    • It did not provide arguments for Zoom type (i.e. Full page, Zoom to Width, Zoom to Height, Two Page Wide)
    • It was light on comments, though the code was quite clear
    The following code addresses the above, building upon Vladimir's great start.  I hope you find it of use.

    using System.Linq; 
    using System.Printing; 
    using System.Windows; 
    using System.Windows.Controls; 
    using System.Windows.Documents; 
    using System.Windows.Markup; 
    using System.Windows.Media; 
    using Telerik.Windows.Controls; 
    using Telerik.Windows.Controls.GridView; 
     
    namespace YourNamespaceHere 
        /// <summary> 
        /// Support Printing Related Methods 
        /// </summary> 
        public static class PrintExtensions 
        { 
            #region ___________ Properties ____________________________________________________________________________________________ 
            /// <summary> 
            /// Zoom Enumeration to specify how pages are stretched in print and preview 
            /// </summary> 
            public enum ZoomType 
            { 
                /// <summary> 
                /// 100% of normal size 
                /// </summary> 
                Full, 
     
                /// <summary> 
                /// Page Width (fit so one page stretches to full width) 
                /// </summary> 
                Width, 
     
                /// <summary> 
                /// Page Height (fit so one page stretches to full height) 
                /// </summary> 
                Height, 
     
                /// <summary> 
                /// Display two columsn of pages 
                /// </summary> 
                TwoWide 
            };        
            #endregion 
            #region ___________ Methods _______________________________________________________________________________________________ 
            /// <summary> 
            /// Print element to a document 
            /// </summary> 
            /// <param name="element">GUI Element to Print</param> 
            /// <param name="dialog">Reference to Print Dialog</param> 
            /// <param name="orientation">Page Orientation (i.e. Portrait vs. Landscape)</param> 
            /// <returns>Destination document</returns> 
            static FixedDocument ToFixedDocument(FrameworkElement element, PrintDialog dialog, PageOrientation orientation = PageOrientation.Portrait) 
            { 
                dialog.PrintTicket.PageOrientation = orientation; 
                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; 
            } 
     
            /// <summary> 
            /// Convert GridView to Printer-Friendly version of a GridView 
            /// </summary> 
            /// <param name="source">Input GridView</param> 
            /// <returns>Printer-Friendly version of source</returns> 
            static GridViewDataControl ToPrintFriendlyGrid(GridViewDataControl source) 
            { 
                RadGridView grid = new RadGridView(); 
     
                grid.ItemsSource = source.ItemsSource; 
                grid.RowIndicatorVisibility = Visibility.Collapsed; 
                grid.ShowGroupPanel = false
                grid.CanUserFreezeColumns = false
                grid.IsFilteringAllowed = false
                grid.AutoExpandGroups = true
                grid.AutoGenerateColumns = false
     
                foreach (GridViewDataColumn 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; 
                    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; 
            } 
     
            /// <summary> 
            /// Perform a Print Preview on GridView source 
            /// </summary> 
            /// <param name="source">Input GridView</param> 
            /// <param name="orientation">Page Orientation (i.e. Portrait vs. Landscape)</param> 
            /// <param name="zoom">Zoom Enumeration to specify how pages are stretched in print and preview</param> 
            public static void PrintPreview(GridViewDataControl source, PageOrientation orientation = PageOrientation.Landscape, ZoomType zoom = ZoomType.TwoWide) 
            { 
                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(), orientation); 
                Zoom(viewer, zoom); 
                window.Content = viewer; 
     
                window.ShowDialog(); 
            } 
     
            /// <summary> 
            /// Constrain val to the range [val_min, val_max] 
            /// </summary> 
            /// <param name="val">Value to be constrained</param> 
            /// <param name="val_min">Minimum that will be returned if val is less than val_min</param> 
            /// <param name="val_max">Maximum that will be returned if val is greater than val_max</param> 
            /// <returns>val in [val_min, val_max]</returns> 
            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; 
            } 
     
            /// <summary> 
            /// Perform a Print on GridView source 
            /// </summary> 
            /// <param name="source">Input GridView</param> 
            /// <param name="showDialog">True to show print dialog before printing</param> 
            /// <param name="orientation">Page Orientation (i.e. Portrait vs. Landscape)</param> 
            /// <param name="zoom">Zoom Enumeration to specify how pages are stretched in print and preview</param> 
            public static void Print(GridViewDataControl source, bool showDialog = true, PageOrientation orientation = PageOrientation.Landscape, ZoomType zoom = ZoomType.TwoWide) 
            { 
                PrintDialog dialog = new PrintDialog(); 
                bool? dialogResult = showDialog ? dialog.ShowDialog() : true
     
                if (dialogResult == true
                { 
                    DocumentViewer viewer = new DocumentViewer(); 
                    viewer.Document = ToFixedDocument(ToPrintFriendlyGrid(source), dialog, orientation); 
                    Zoom(viewer, zoom); 
                    dialog.PrintDocument(viewer.Document.DocumentPaginator, ""); 
                } 
            } 
     
            /// <summary> 
            /// Scale viewer to size specified by zoom 
            /// </summary> 
            /// <param name="viewer">Document to zoom</param> 
            /// <param name="zoom">Zoom Enumeration to specify how pages are stretched in print and preview</param> 
            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
                } 
            } 
            #endregion 
        } 
  2. Vlad
    Admin
    Vlad avatar
    11100 posts

    Posted 26 May 2010 Link to this post

    Hi Brian,

    Great post! I've added 5000 Telerik points to your account.

    Best wishes,
    Vlad
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  3. frdotnet
    frdotnet avatar
    5 posts
    Member since:
    Jul 2010

    Posted 23 Jul 2010 Link to this post

    Quick question. The grid does not show the entire content of the cells. so when the grid is created I added the line 
    grid.width = gridviewlength.auto. But with this , the grids width after expanding the text of all the columns is not known, so it does not continue printing rest of the columns on next page . Any ideas ?
  4. Vlad
    Admin
    Vlad avatar
    11100 posts

    Posted 29 Jul 2010 Link to this post

    Hi frdotnet,

     Printing rest of the columns on the next page will not be a trivial task unfortunately. The only solution I can think of currently is to hide columns out of view and print only these columns explicitly on the next page (hide other columns). 

    All the best,
    Vlad
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  5. Christian
    Christian avatar
    7 posts
    Member since:
    Sep 2010

    Posted 18 Oct 2010 Link to this post

    element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

    This line of code (inside ToFixedDocument method) produces an error, hangs my program. What could be the problem?
  6. Vlad
    Admin
    Vlad avatar
    11100 posts

    Posted 19 Oct 2010 Link to this post

    Hello,

     Can you post more info about the error?

    Greetings,
    Vlad
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  7. Roman
    Roman avatar
    1 posts
    Member since:
    Jan 2011

    Posted 19 Jan 2011 Link to this post

    Hi,

    I have similar problem as Christian mentioned above-  "element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
    This line of code (inside ToFixedDocument method) produces an error, hangs my program. What could be the problem? "

    I get InvalidOpeartionException - "Specified element is already the logical child of another element. Disconnect it first."
    Most likely it happens without nested child grids.  Any help with this?
  8. Alan
    Alan avatar
    47 posts
    Member since:
    Jun 2009

    Posted 24 Feb 2011 Link to this post

    I have this same problem when printing.

    System.InvalidOperationException occurred
      Message=Specified element is already the logical child of another element. Disconnect it first.
      Source=PresentationFramework
      StackTrace:
           at System.Windows.FrameworkElement.ChangeLogicalParent(DependencyObject newParent)
      InnerException: 


    I am printing a RadTreeListVIew using this example.
  9. Yordanka
    Admin
    Yordanka avatar
    634 posts

    Posted 28 Feb 2011 Link to this post

    Hello,

    Could you open a separate support ticket and attach the sample project where this exception can be seen ? We have tried to reproduce it locally but unfortunately, we could not.
     
    All the best,
    Yordanka
    the Telerik team
    Registration for Q1 2011 What’s New Webinar Week is now open. Mark your calendar for the week starting March 21st and book your seat for a walk through all the exciting stuff we ship with the new release!
  10. Alan
    Alan avatar
    47 posts
    Member since:
    Jun 2009

    Posted 28 Feb 2011 Link to this post

    Yordanka,

    I figured out what the problem was. If you set the column header (in the xaml) to be a be TextBlock and then add newColumn.Header = column.Header inside the for loop, you will see the problem. 

    foreach (GridViewDataColumn column in source.Columns.OfType<GridViewDataColumn>()) 
    {
    ...
    newColumn.Header = column.Header;
    }

    I was able to work around it by copying the TextBlock's "Text" property to the newColumn.Header, and then it worked.
    Let me know if you still need a support ticket, and I'll create one.
  11. Yordanka
    Admin
    Yordanka avatar
    634 posts

    Posted 02 Mar 2011 Link to this post

    Hi Alan,

    Thank you for cooperation.

    In your case, the TextBlock element is already part of the column's visual tree. So, you cannot connect it to nextColumn's visual tree in this way. You need first to disconnect it from column's visual tree (column.Header = null;) or to use the logic pointed by you. 
     
    All the best,
    Yordanka
    the Telerik team
    Registration for Q1 2011 What’s New Webinar Week is now open. Mark your calendar for the week starting March 21st and book your seat for a walk through all the exciting stuff we ship with the new release!
  12. Yogesh
    Yogesh avatar
    6 posts
    Member since:
    May 2011

    Posted 14 Jul 2011 Link to this post

    hello,

    PROJECT DESCRIPTION
     
    I recently wanted to enable my GridView to perform print and print preview functions.  The example a Yogesh Post about Print Preview was a great start, but it had the following limitations:


    using System.Linq;
    using System.Printing;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Markup;
    using System.Windows.Media;
    using Telerik.Windows.Controls;
    using Telerik.Windows.Controls.GridView;
    using System;


    namespace Enaptive.Synergy.DeliveryPlanner
    {
        public static class PrintExtensions
        {
            static string PageTitle = "";


            static FixedDocument ToFixedDocument(FrameworkElement element, PrintDialog dialog)
            {
                var capabilities = dialog.PrintQueue.GetPrintCapabilities(dialog.PrintTicket);
                //var pageSize = new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight);
                var extentSize = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);


                var fixedDocument = new FixedDocument();
                fixedDocument.PrintTicket = dialog.PrintTicket;
                element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                element.Arrange(new Rect(new Point(0, 0), element.DesiredSize));
                var totalHeight = element.DesiredSize.Height;
                var totalWidth = element.DesiredSize.Width;
                //var yOffset = 0d;
                //while (yOffset < totalHeight)
                //{
                //    var brush = new VisualBrush(element)
                //    {
                //        Stretch = Stretch.None,
                //        AlignmentX = AlignmentX.Left,
                //        AlignmentY = AlignmentY.Top,
                //        ViewboxUnits = BrushMappingMode.Absolute,
                //        TileMode = TileMode.None,
                //        Viewbox = new Rect(0, yOffset, extentSize.Width, extentSize.Height)
                //    };


                //    var pageContent = new PageContent();
                //    var page = new FixedPage();
                //    ((IAddChild)pageContent).AddChild(page);


                //    fixedDocument.Pages.Add(pageContent);
                //    page.Width = pageSize.Width;
                //    page.Height = pageSize.Height;


                //    // add a title to the page
                //    double top = capabilities.PageImageableArea.OriginHeight;
                //    TextBlock pageText = new TextBlock();
                //    pageText.Text = PageTitle;
                //    pageText.FontSize = 24; 
                //    pageText.Margin = new Thickness(5); 
                //    FixedPage.SetLeft(pageText, top);
                //    pageText.Width = extentSize.Width;                
                //    page.Children.Add(pageText);
                //    top += 18;


                //    TextBlock dateText = new TextBlock();
                //    dateText.Text = "As of " + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                //    dateText.FontStyle = FontStyles.Italic;
                //    dateText.FontSize = 10;
                //    dateText.Margin = new Thickness(5); 
                //    FixedPage.SetLeft(dateText, capabilities.PageImageableArea.OriginWidth);
                //    FixedPage.SetTop(dateText, top);
                //    dateText.Width = extentSize.Width;
                //    page.Children.Add(dateText);
                //    top += 24;


                //    var canvas = new Canvas();
                //    FixedPage.SetLeft(canvas, capabilities.PageImageableArea.OriginWidth);
                //    FixedPage.SetTop(canvas, top);
                //    canvas.Width = extentSize.Width;
                //    canvas.Height = extentSize.Height-top;
                //    canvas.Background = brush;


                //    page.Children.Add(canvas);


                //    yOffset += extentSize.Height;
                //}


                var yOffset = 0d;
                var xOffset = 0d;


                //double tmpHeight = 0;
                int j = 0, k = 0, i;
                while (yOffset < totalHeight)
                {
                    double tmpHeight = 0;
                    while (xOffset < totalWidth)
                    {
                        //for Width
                        double tmpWidth = 0;
                        var tmpElementWidth = (GridViewDataControl)element;
                        for (i = j; i < tmpElementWidth.Columns.Count; i++)
                        {
                            tmpWidth += tmpElementWidth.Columns[i].ActualWidth;
                            if (tmpWidth > extentSize.Width)
                            {
                                tmpWidth = extentSize.Width - (tmpWidth - tmpElementWidth.Columns[i].ActualWidth);
                                j = i - 1;
                                break;
                            }


                        }
                        if ((i < tmpElementWidth.Columns.Count) == false)
                        {
                            tmpWidth = 0;
                            j = 0;
                        }
                        //


                        //for Height
                        //var tmpElementHeight = (GridViewDataControl)element;
                        //for (i = k; i < tmpElementHeight.Items.Count; i++)
                        //{
                        //    tmpHeight += tmpElementHeight.RowHeight;
                        //    if (tmpHeight >= extentSize.Height)
                        //    {
                        //        tmpHeight = extentSize.Height - (tmpHeight - tmpElementHeight.RowHeight);
                        //        k = i - 1;
                        //        break;
                        //    }
                        //}
                        //if ((i < tmpElementWidth.Columns.Count) == false)
                        //{
                        //    tmpHeight = 0;
                        //    k = 0;
                        //}
                        //


                        var brush = new VisualBrush(element)
                        {
                            Stretch = Stretch.None,
                            AlignmentX = AlignmentX.Left,
                            AlignmentY = AlignmentY.Top,
                            ViewboxUnits = BrushMappingMode.Absolute,
                            TileMode = TileMode.None,
                            Viewbox = new Rect(xOffset, yOffset, extentSize.Width - tmpWidth, extentSize.Height - tmpHeight)
                        };


                        var pageContent = new PageContent();
                        var page = new FixedPage();
                        page.PrintTicket = dialog.PrintTicket;
                        ((IAddChild)pageContent).AddChild(page);
                        fixedDocument.Pages.Add(pageContent);
                        page.Width = extentSize.Width;
                        page.Height = extentSize.Height;


                        // add a title to the page
                        double top = capabilities.PageImageableArea.OriginHeight;
                        TextBlock pageText = new TextBlock();
                        pageText.Text = PageTitle;
                        pageText.FontSize = 24;
                        pageText.Margin = new Thickness(5);
                        FixedPage.SetLeft(pageText, top);
                        pageText.Width = extentSize.Width;
                        page.Children.Add(pageText);
                        top += 30;


                        TextBlock dateText = new TextBlock();
                        dateText.Text = "As of " + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                        dateText.FontStyle = FontStyles.Italic;
                        dateText.FontSize = 10;
                        dateText.Margin = new Thickness(5);
                        FixedPage.SetLeft(dateText, capabilities.PageImageableArea.OriginWidth);
                        FixedPage.SetTop(dateText, top);
                        dateText.Width = extentSize.Width;
                        page.Children.Add(dateText);
                        top += 24;


                        var canvas = new Canvas();
                        FixedPage.SetLeft(canvas, capabilities.PageImageableArea.OriginWidth);
                        FixedPage.SetTop(canvas, top);
                        canvas.Width = extentSize.Width - tmpWidth;
                        canvas.Height = extentSize.Height - top - tmpHeight;
                        canvas.Background = brush;


                        page.Children.Add(canvas);


                        xOffset += extentSize.Width - tmpWidth;
                        tmpHeight = 0;
                    }
                    xOffset = 0d;
                    yOffset += extentSize.Height - tmpHeight;
                }
                return fixedDocument;
            }


            static GridViewDataControl ToPrintFriendlyGrid(GridViewDataControl source)
            {
                var grid = new RadGridView()
                {
                    ItemsSource = source.ItemsSource,
                    RowIndicatorVisibility = Visibility.Collapsed,
                    ShowGroupPanel = false,
                    CanUserFreezeColumns = false,
                    IsFilteringAllowed = false,
                    AutoExpandGroups = true,
                    AutoGenerateColumns = false,
                };


                foreach (var column in source.Columns.OfType<GridViewDataColumn>())
                {
                    string HideRedToggleButtonColumn = column.Header.ToString();
                    if (HideRedToggleButtonColumn != "Telerik.Windows.Controls.RadToggleButton Content: IsChecked:False" && HideRedToggleButtonColumn != "Telerik.Windows.Controls.RadToggleButton Content: IsChecked:True")
                    {
                        //MessageBox.Show(column.UniqueName);
                        var newColumn = new GridViewDataColumn();
                        newColumn.DataMemberBinding = new System.Windows.Data.Binding(column.UniqueName);
                        //newColumn.Width.IsSizeToCells = column.Width.IsSizeToCells;
                        //newColumn.DisplayIndex = column.DisplayIndex; 
                        //newColumn.DataType = typeof(string);
                        newColumn.Header = column.Header;
                        newColumn.Width = column.ActualWidth;


                        //newColumn.DisplayIndex = column.DisplayIndex;
                        newColumn.DataMemberBinding = column.DataMemberBinding; // Better to just copy the references to get all the custom formatting 
                        newColumn.DataFormatString = column.DataFormatString;
                        grid.Columns.Add(newColumn);
                    }
                }


                //foreach (GridViewDataColumn colms in source.Items.OfType<GridViewDataColumn>())
                //{
                //    var newColumn = new GridViewDataColumn();
                //    newColumn.DataMemberBinding = new System.Windows.Data.Binding(colms.UniqueName);
                //    grid.Columns.Add(newColumn);
                //}


                //for (int i = 0; i < source.Columns.Count; i++)
                //{
                //    var newColumn = new GridViewDataColumn();
                //    newColumn.DataMemberBinding = new System.Windows.Data.Binding(source.Columns[i].UniqueName);
                //    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 static void PrintPreview(this GridViewDataControl source, string pageTitle)
            {
                PageTitle = pageTitle;
                var dialog = new PrintDialog();
                dialog.PrintQueue = LocalPrintServer.GetDefaultPrintQueue();
                dialog.PrintTicket = dialog.PrintQueue.DefaultPrintTicket;
                //for Landscape
                dialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
                var window = new Window()
                {
                    Title = "Print Preview - " + pageTitle,
                    Content = new DocumentViewer()
                    {
                        Document = ToFixedDocument(ToPrintFriendlyGrid(source), dialog)
                    }
                };


                window.ShowDialog();
            }


            public static void Print(this GridViewDataControl source, bool showDialog, string pageTitle)
            {
                PageTitle = pageTitle;


                var dialog = new PrintDialog();
                dialog.PrintQueue = LocalPrintServer.GetDefaultPrintQueue();
                dialog.PrintTicket = dialog.PrintQueue.DefaultPrintTicket;
                //for Landscape
                dialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
                var dialogResult = showDialog ? dialog.ShowDialog() : true;


                if (dialogResult == true)
                {
                    var viewer = new DocumentViewer();
                    viewer.Document = ToFixedDocument(ToPrintFriendlyGrid(source), dialog);
                    dialog.PrintDocument(viewer.Document.DocumentPaginator, "");
                }
            }
        }
    }

    regards
    Yogesh
  13. Marco Beretta
    Marco Beretta avatar
    1 posts
    Member since:
    Sep 2012

    Posted 28 Mar 2012 Link to this post

    Hi,
    I was trying to use the Print and printpreview code which published at the start of the discussion. its great to see the result. Except one small issue. At the end of each page, half of the row displayed in the first page, and the remaining half displaying in next page. Is there any way to control this display?

    Thanks,
    Marco
  14. Michael
    Michael avatar
    105 posts
    Member since:
    Nov 2010

    Posted 14 Apr 2012 Link to this post

    OK

    How do you do this with MVC model?

    So far I have 
    <telerik:RadButton Content="Print" Command="{Binding Path=GridPrint.Command}"  Margin="25,5,5,5" Padding="5" Width="150" />
                                          <telerik:RadButton Content="Print Preview" Command="{Binding Path=GridPreview.Command}" Margin="25,5,5,5" Padding="5" Width="150" />OK

    but how do i send a reference to the grid from this?
  15. Ramy
    Ramy avatar
    1 posts
    Member since:
    Feb 2012

    Posted 23 Sep 2012 Link to this post

    This Code is wonderfull, however I used this code with Radgridview that is bounded with Large amount of data. it takes more than ten minutes and still the Dialog is not shown.

    If I tried this example with small records, it will work.

    Any Help!

    Thanks for Advance.
  16. Dimitrina
    Admin
    Dimitrina avatar
    3769 posts

    Posted 24 Dec 2012 Link to this post

    Hello,

    Please note that the approach suggested initially almost 2 years ago is not supported any more.

    I have attached an updated project showing how you can currently implement a Print and PrintPreview with the help of RadDocument and RadRichTextBox.

    Kind regards,
    Didie
    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

  17. Rosen
    Rosen avatar
    1 posts
    Member since:
    Feb 2013

    Posted 09 Feb 2013 Link to this post

    Hello,


    I have some questions about the latest printing project. How can I add more controls to the printing document ? For example a textblock below and above the gridview ? Also is there any way to center the content in the gridview cells and headers before printing ?
  18. Dimitrina
    Admin
    Dimitrina avatar
    3769 posts

    Posted 11 Feb 2013 Link to this post

    Hello,


    You can find the CreateDocument method and check how the document is created step by step. Then change it to add additional elements (for example the value for the TextBlock).

    In order to be able to better understand and extend the example I suggest you to go through the articles about using the RadDocument and about the document viewer control - RadRichTextBox.   

    All the best,
    Didie
    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

  19. Pankaj
    Pankaj avatar
    24 posts
    Member since:
    Apr 2013

    Posted 29 Apr 2013 Link to this post

    Hi all i have problem in google chrome , i am using the telerik rad grid on click on print button it is showing the popup "Unable to perform the Print operation"
    And its working fine in all the browser except chrome

    the aspx code is

    <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="TelerikCustomReport" Title="<%$ Resources:ReportsPageTitle%>" Codebehind="TelerikCustomReport.aspx.cs" %>
     
    <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
    <%@ Register Src="ucReports.ascx" TagName="ucReports" TagPrefix="uc1" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server">
        </telerik:RadAjaxLoadingPanel>
        <telerik:RadAjaxManager ID="ajax" runat="server">
            <AjaxSettings>
                <%--   <telerik:AjaxSetting AjaxControlID="txtFromdate">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="tblDateRange" LoadingPanelID="RadAjaxLoadingPanel1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
                <telerik:AjaxSetting AjaxControlID="txtToDate">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="tblDateRange" LoadingPanelID="RadAjaxLoadingPanel1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
                <telerik:AjaxSetting AjaxControlID="rdoDayList">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="tblDateRange" LoadingPanelID="RadAjaxLoadingPanel1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
                <telerik:AjaxSetting AjaxControlID="chkFullDay">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="tblDateRange" LoadingPanelID="RadAjaxLoadingPanel1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>--%>
                <telerik:AjaxSetting AjaxControlID="btnRunReport">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="tblDateRange" LoadingPanelID="RadAjaxLoadingPanel1" />
                        <telerik:AjaxUpdatedControl ControlID="lstUnits" />
                        <telerik:AjaxUpdatedControl ControlID="lstGroups" />
                        <telerik:AjaxUpdatedControl ControlID="lstRegions" />
                        <telerik:AjaxUpdatedControl ControlID="lstAsset" />
                        <telerik:AjaxUpdatedControl ControlID="dlChooseItems" />
                        <telerik:AjaxUpdatedControl ControlID="gvReportUnit" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>
        <table width="100%" border="0" cellspacing="0" cellpadding="0" class="TableNormal">
            <tr>
                <td valign="top">
                    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="TableNormal">
                        <tr>
                            <td width="280" valign="top">
                                <uc1:ucReports ID="ucReports1" runat="server"></uc1:ucReports>
                            </td>
                            <td width="900" valign="top">
                                <table width="100%" border="0" cellspacing="0" cellpadding="0" class="TableNormal">
                                    <tr>
                                        <td class="in_box_topleft">
                                        </td>
                                        <td class="in_box_topbg">
                                        </td>
                                        <td class="in_box_topright">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="in_box_leftbg">
                                        </td>
                                        <td class="in_box_pad">
                                            <table width="100%" border="0" class="TableNormal">
                                                <tr>
                                                    <td width="100%" valign="top">
                                                        <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
                                                            <table width="99%" border="0" cellpadding="0" cellspacing="0" class="TableNormal">
                                                                <tr>
                                                                    <td height="25" style="width18px">
                                                                        <img src="<%=GPSGeneralSettings.Images%>/titlebl.gif" />
                                                                    </td>
                                                                    <td valign="middle">
                                                                        <h1 class="h1Normal">
                                                                            <asp:Literal ID="litReportHeading" runat="server" Text="<%$ Resources:litReportHeading%>" /></h1>
                                                                    </td>
                                                                    <td align="right">
                                                                        <img src="<%=GPSGeneralSettings.Images%>/title_dots.gif" width="29" height="23" />
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td colspan="3" class="title_line" style="height15px">
                                                                    </td>
                                                                </tr>
                                                            </table>
                                                        </telerik:RadCodeBlock>
                                                    </td>
                                                </tr>
                                            </table>
                                            <table width="100%" border="0" class="TableNormal">
                                                <tr>
                                                    <td align="center" valign="top" width="99%">
                                                        <table width="99%" border="0" cellpadding="0" cellspacing="0" class="TableNormal">
                                                            <tr>
                                                                <td class="ch_mn_1">
                                                                </td>
                                                                <td class="ch_mn_2">
                                                                </td>
                                                                <td class="ch_mn_3">
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <td class="ch_mn_4">
                                                                    &nbsp;
                                                                </td>
                                                                <td valign="top">
                                                                    <telerik:RadCodeBlock ID="RadCodeBlock2" runat="server">
                                                                        <table width="100%" border="0" cellspacing="1" cellpadding="2" class="TableNormal"
                                                                            id="tblDateRange" runat="server">
                                                                            <tr>
                                                                                <td class="inner_title">
                                                                                    <strong>
                                                                                        <asp:Literal ID="litSelectDateRange" runat="server" Text="<%$ Resources:litSelectDateRange%>" /></strong>
                                                                                </td>
                                                                            </tr>
                                                                            <tr>
                                                                                <td valign="top">
                                                                                    <table width="100%" border="0" cellspacing="1" cellpadding="1" class="TableNormal">
                                                                                        <tr>
                                                                                            <td class="rgt_lab" style="padding-left70px;">
                                                                                                <asp:Literal ID="litFromdate" runat="server" Text="<%$ Resources:litFromdate%>" />:
                                                                                            </td>
                                                                                            <td class="lft_lab" width="100px">
                                                                                                <telerik:RadDatePicker ID="txtFromdate" runat="server" Width="90px" AutoPostBack="false">
                                                                                                    <ClientEvents OnDateSelected="OnFromDateSelected"></ClientEvents>
                                                                                                </telerik:RadDatePicker>
                                                                                                <asp:RequiredFieldValidator ID="rfvtxtFromdate" runat="server" ControlToValidate="txtFromdate"
                                                                                                    Display="Dynamic" ErrorMessage="*" SetFocusOnError="True" ToolTip="<%$ Resources:rfvtxtFromdate%>"
                                                                                                    ValidationGroup="valReport" />
                                                                                                <asp:CompareValidator ID="cmvtxtFromdate" runat="server" ErrorMessage="*" ToolTip="<%$ Resources:rfvtxtFromdate%>"
                                                                                                    ControlToValidate="txtFromdate" Operator="DataTypeCheck" Display="Dynamic" SetFocusOnError="True"
                                                                                                    Type="Date" ValidationGroup="valReport" />
                                                                                            </td>
                                                                                            <td class="rgt_lab">
                                                                                                <asp:Literal ID="litFromTime" runat="server" Text="<%$ Resources:litTime%>" />:
                                                                                            </td>
                                                                                            <td class="lft_lab" width="60%">
                                                                                                <telerik:RadTimePicker ID="txtWeekDaysFrom" runat="Server" Width="80px" TimeView-StartTime="00:00:00"
                                                                                                    TimeView-Interval="00:30:00" TimeView-EndTime="23:45:00" />
                                                                                            </td>
                                                                                        </tr>
                                                                                        <tr>
                                                                                            <td class="rgt_lab" style="padding-left70px;">
                                                                                                <asp:Literal ID="litToDate" runat="server" Text="<%$ Resources:litToDate%>" />:
                                                                                            </td>
                                                                                            <td class="lft_lab">
                                                                                                <telerik:RadDatePicker ID="txtToDate" runat="server" Width="90px" AutoPostBack="false">
                                                                                                    <ClientEvents OnDateSelected="OnToDateSelected"></ClientEvents>
                                                                                                </telerik:RadDatePicker>
                                                                                                <asp:RequiredFieldValidator ID="rfvtxtToDate" runat="server" ControlToValidate="txtToDate"
                                                                                                    Display="Dynamic" ErrorMessage="*" SetFocusOnError="True" ToolTip="<%$ Resources:rfvtxtFromdate%>"
                                                                                                    ValidationGroup="valReport" />
                                                                                                <asp:CompareValidator ID="cmvtxtToDate" runat="server" ErrorMessage="*" ToolTip="<%$ Resources:rfvtxtFromdate%>"
                                                                                                    ControlToValidate="txtToDate" Operator="DataTypeCheck" Display="Dynamic" SetFocusOnError="True"
                                                                                                    Type="Date" ValidationGroup="valReport" />
                                                                                            </td>
                                                                                            <td class="rgt_lab">
                                                                                                <asp:Literal ID="litTotime" runat="server" Text="<%$ Resources:litTime%>" />:
                                                                                            </td>
                                                                                            <td class="lft_lab">
                                                                                                <telerik:RadTimePicker ID="txtWeekDaysTo" runat="Server" Width="80px" TimeView-StartTime="00:00:00"
                                                                                                    TimeView-Interval="00:30:00" TimeView-EndTime="23:45:00" />
                                                                                            </td>
                                                                                        </tr>
                                                                                        <tr>
                                                                                            <td colspan="3" align="left">
                                                                                                <img src="<%=GPSGeneralSettings.Images%>/spc.png" width="1" height="5" />
                                                                                            </td>
                                                                                            <td class="lft_lab" valign="top">
                                                                                                <asp:CheckBox ID="chkFullDay" Text="<%$ Resources:chkFullDay%>" runat="server" AutoPostBack="false"
                                                                                                    onclick="CheckChanged(this);" />
                                                                                            </td>
                                                                                        </tr>
                                                                                        <tr>
                                                                                            <td class="lft_lab" valign="top" colspan="4" align="left" style="padding-left20px">
                                                                                                <asp:RadioButtonList ID="rdoDayList" runat="Server" RepeatDirection="horizontal"
                                                                                                    AutoPostBack="false" onclick="SelectionChanged(this);">
                                                                                                    <%-- OnSelectedIndexChanged="rdoDayList_SelectedIndexChanged">--%>
                                                                                                    <asp:ListItem Text="<%$ Resources:chkliNone%>" Value="None" />
                                                                                                    <asp:ListItem Text="<%$ Resources:chkliToday%>" Value="Today" />
                                                                                                    <asp:ListItem Text="<%$ Resources:chkliYesterDay%>" Value="YesterDay" />
                                                                                                    <asp:ListItem Text="<%$ Resources:chkliThisWeek%>" Value="ThisWeek" />
                                                                                                    <asp:ListItem Text="<%$ Resources:chkliLastWeek%>" Value="LastWeek" />
                                                                                                    <asp:ListItem Text="<%$ Resources:chkliMonthtoDate%>" Value="Month to Date" />
                                                                                                    <asp:ListItem Text="<%$ Resources:chkliLastMonth%>" Value="Last Month" />
                                                                                                </asp:RadioButtonList>
                                                                                            </td>
                                                                                        </tr>
                                                                                        <tr id="trRoadName" runat="server" visible="false">
                                                                                            <td class="rgt_lab" valign="middle">
                                                                                                <asp:Literal ID="Literal2" runat="server" Text="<%$ Resources:litRoadName%>" />:
                                                                                            </td>
                                                                                            <td class="lft_lab" colspan="3">
                                                                                                <telerik:RadTextBox ID="txtRoadName" runat="server" Width="200px" />&nbsp;(<asp:Literal
                                                                                                    ID="Literal3" runat="server" Text="<%$ Resources:litRoadNameSeperator%>" />&nbsp;)
                                                                                            </td>
                                                                                        </tr>
                                                                                        <tr id="trThreshold" runat="server">
                                                                                            <td class="rgt_lab">
                                                                                                <asp:Literal ID="litThreshold" runat="server" Text="<%$ Resources:litThreshold%>" />:
                                                                                            </td>
                                                                                            <td class="lft_lab" colspan="3">
                                                                                                <telerik:RadTextBox ID="txtThreshold" runat="server" Width="80px" />
                                                                                                <asp:CompareValidator ID="cmvtxtThreshold" runat="server" ErrorMessage="*" ToolTip="<%$ Resources:cmvtxtThreshold %>"
                                                                                                    ControlToValidate="txtThreshold" Operator="DataTypeCheck" Display="Dynamic" SetFocusOnError="True"
                                                                                                    Type="Integer" ValidationGroup="valReport" />
                                                                                            </td>
                                                                                        </tr>
                                                                                        <tr id="includeidleevent" runat="server" visible="false">
                                                                                            <td align="left" colspan="3">
                                                                                                <img src="<%=GPSGeneralSettings.Images%>/spc.png" width="1" height="5" />
                                                                                            </td>
                                                                                            <td class="lft_lab" valign="top">
                                                                                                <asp:CheckBox ID="chkincludeidleevent" runat="server" Text="<%$ Resources:litincludeidle%>" />
                                                                                            </td>
                                                                                        </tr>
                                                                                    </table>
                                                                                </td>
                                                                            </tr>
                                                                        </table>
                                                                    </telerik:RadCodeBlock>
                                                                </td>
                                                                <td class="ch_mn_5">
                                                                    &nbsp;
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <td class="ch_mn_6">
                                                                </td>
                                                                <td class="ch_mn_7">
                                                                </td>
                                                                <td class="ch_mn_8">
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td align="center" valign="top" width="99%">
                                                        <table width="99%" border="0" cellpadding="0" cellspacing="0" class="TableNormal">
                                                            <tr>
                                                                <td class="ch_mn_1">
                                                                </td>
                                                                <td class="ch_mn_2">
                                                                </td>
                                                                <td class="ch_mn_3">
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <td class="ch_mn_4">
                                                                    &nbsp;
                                                                </td>
                                                                <td valign="top">
                                                                    <telerik:RadCodeBlock ID="RadCodeBlock3" runat="server">
                                                                        <table width="100%" border="0" cellspacing="1" cellpadding="2" class="TableNormal">
                                                                            <tr>
                                                                                <td class="inner_title">
                                                                                    <strong>
                                                                                        <asp:Literal ID="litSelectUnit" runat="server" Text="<%$ Resources:litSelectUnit%>" /></strong>
                                                                                </td>
                                                                            </tr>
                                                                            <tr>
                                                                                <td class="lft_lab">
                                                                                    <asp:Literal ID="litHoldCtrl" runat="server" Text="<%$ Resources:General, litHoldCtrl%>" />
                                                                                </td>
                                                                            </tr>
                                                                            <tr>
                                                                                <td valign="top">
                                                                                    <table width="100%" border="0" cellspacing="1" cellpadding="2" class="TableNormal">
                                                                                        <tr>
                                                                                            <td class="rgt_lab" valign="top">
                                                                                                <asp:Literal ID="litUnits" runat="server" Text="<%$ Resources:litUnits%>" />:
                                                                                            </td>
                                                                                            <td class="lft_lab">
                                                                                                <telerik:RadListBox ID="lstUnits" runat="Server" SelectionMode="Multiple" Width="115px"
                                                                                                    Height="150px" />
                                                                                            </td>
                                                                                            <td class="rgt_lab" valign="top" id="tdAsset" runat="server">
                                                                                                <asp:Literal ID="litAsset" runat="server" Text="<%$ Resources:litAsset%>" />:
                                                                                            </td>
                                                                                            <td class="lft_lab" id="littdAsset" runat="server">
                                                                                                <telerik:RadListBox ID="lstAsset" runat="Server" SelectionMode="Multiple" Width="115px"
                                                                                                    Height="150px" />
                                                                                            </td>
                                                                                            <td class="rgt_lab" valign="top">
                                                                                                <asp:Literal ID="litGroups" runat="server" Text="<%$ Resources:litGroups%>" />:
                                                                                            </td>
                                                                                            <td class="lft_lab">
                                                                                                <telerik:RadListBox ID="lstGroups" runat="Server" SelectionMode="Multiple" Width="115px"
                                                                                                    Height="150px" />
                                                                                            </td>
                                                                                            <td class="rgt_lab" valign="top">
                                                                                                <asp:Literal ID="litRegions" runat="server" Text="<%$ Resources:litRegions%>" />:
                                                                                            </td>
                                                                                            <td class="lft_lab">
                                                                                                <telerik:RadListBox ID="lstRegions" runat="Server" SelectionMode="Multiple" Width="115px"
                                                                                                    Height="150px" />
                                                                                            </td>
                                                                                        </tr>
                                                                                    </table>
                                                                                </td>
                                                                            </tr>
                                                                        </table>
                                                                    </telerik:RadCodeBlock>
                                                                </td>
                                                                <td class="ch_mn_5">
                                                                    &nbsp;
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <td class="ch_mn_6">
                                                                </td>
                                                                <td class="ch_mn_7">
                                                                </td>
                                                                <td class="ch_mn_8">
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td align="center" valign="top" width="99%">
                                                        <table width="99%" border="0" cellpadding="0" cellspacing="0" class="TableNormal">
                                                            <tr>
                                                                <td class="ch_mn_1">
                                                                </td>
                                                                <td class="ch_mn_2">
                                                                </td>
                                                                <td class="ch_mn_3">
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <td class="ch_mn_4">
                                                                    &nbsp;
                                                                </td>
                                                                <td valign="top">
                                                                    <telerik:RadCodeBlock ID="RadCodeBlock4" runat="server">
                                                                        <table width="100%" border="0" cellspacing="1" cellpadding="2" class="TableNormal">
                                                                            <tr>
                                                                                <td class="inner_title">
                                                                                    <strong>
                                                                                        <asp:Literal ID="litChooseItems" runat="server" Text="<%$ Resources:litChooseItems%>" /></strong>
                                                                                </td>
                                                                            </tr>
                                                                            <tr>
                                                                                <td valign="top">
                                                                                    <table width="100%" border="0" cellspacing="1" cellpadding="2" class="TableNormal">
                                                                                        <tr>
                                                                                            <td class="lft_lab">
                                                                                                <asp:DataList Width="100%" ID="dlChooseItems" HeaderStyle-HorizontalAlign="Center"
                                                                                                    RepeatDirection="Vertical" RepeatColumns="5" ItemStyle-HorizontalAlign="left"
                                                                                                    runat="server" border="0" CellSpacing="1" CellPadding="2">
                                                                                                    <ItemStyle HorizontalAlign="Left" />
                                                                                                    <HeaderStyle HorizontalAlign="Center" />
                                                                                                    <ItemTemplate>
                                                                                                        <asp:CheckBox ID="chkChooseItems" runat="server" Text='<%#Eval("FieldName") %>' />
                                                                                                    </ItemTemplate>
                                                                                                </asp:DataList>
                                                                                            </td>
                                                                                        </tr>
                                                                                    </table>
                                                                                </td>
                                                                            </tr>
                                                                        </table>
                                                                    </telerik:RadCodeBlock>
                                                                </td>
                                                                <td class="ch_mn_5">
                                                                    &nbsp;
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <td class="ch_mn_6">
                                                                </td>
                                                                <td class="ch_mn_7">
                                                                </td>
                                                                <td class="ch_mn_8">
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td valign="middle">
                                                        <table width="100%" border="0" cellspacing="0" cellpadding="0" class="TableNormal">
                                                            <tr>
                                                                <td align="right" valign="middle">
                                                                    <asp:Button ID="btnRunReport" runat="server" Text="Run Report" CssClass="inputbutton"
                                                                        OnClick="btnRunReport_Click" ValidationGroup="valReport" />
                                                                </td>
                                                                <%--<td width="100%" class="rgt_lab" valign="middle">
                                                                    <asp:Literal ID="litSaveCustomReport" runat="server" Text="<%$Resources:litSaveReportas %>" />
                                                                    <asp:TextBox ID="txtSaveMyReport" runat="server" CssClass="inputNormal" />
                                                                    <asp:Button ID="btnSaveMyReport" runat="server" Text="Save" CssClass="inputbutton" />
                                                                </td>--%>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                        <td class="in_box_rightbg">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="in_box_botleft">
                                        </td>
                                        <td class="in_box_botbg">
                                        </td>
                                        <td class="in_box_botright">
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td>
                    <telerik:RadCodeBlock ID="RadCodeBlock6" runat="server">
                        <img src="<%=GPSGeneralSettings.Images%>/spc.png" width="1" height="5" />
                    </telerik:RadCodeBlock>
                </td>
            </tr>
            <tr>
                <td valign="top" align="left">
                    <asp:ImageButton ID="imgPrint" runat="server" ImageUrl="App_Themes/Default/Images/imgPrintMap.png"
                        CssClass="print" OnClick="imgPrint_click" />
                </td>
            </tr>
            <tr>
                <td>
                  <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
                    <telerik:RadGrid Width="100%" HeaderStyle-Height="22px" HeaderStyle-HorizontalAlign="Left"
                        GridLines="Horizontal" DataKeyNames="UnitId" AutoGenerateColumns="false" AllowSorting="true"
                        MasterTableView-HierarchyDefaultExpanded="true" AllowPaging="false" ID="gvReportUnit"
                        runat="server" OnDetailTableDataBind="gvReportUnit_DetailTableDataBind" OnSortCommand="gvReportUnit_SortCommand">
                        <PagerStyle Mode="NumericPages"></PagerStyle>
                        <ClientSettings AllowColumnsReorder="true" ReorderColumnsOnClient="true">
                        </ClientSettings>
                        <MasterTableView AllowSorting="true" DataKeyNames="UnitId" Width="100%">
                            <Columns>
                                <telerik:GridBoundColumn DataField="UnitId" Visible="false">
                                </telerik:GridBoundColumn>
                                <telerik:GridTemplateColumn HeaderText="Unit ID" ItemStyle-CssClass="ItemStyle" ItemStyle-VerticalAlign="Top"
                                    ItemStyle-HorizontalAlign="Left" SortExpression="UnitNameId" HeaderStyle-HorizontalAlign="Left"
                                    ItemStyle-Width="100%">
                                    <ItemTemplate>
                                        <%# Eval("UnitNameId"%>
                                    </ItemTemplate>
                                </telerik:GridTemplateColumn>
                            </Columns>
                            <DetailTables>
                                <telerik:GridTableView AllowPaging="false" AutoGenerateColumns="false" AllowSorting="false"
                                    GridLines="Horizontal" Width="100%" runat="server">
                                </telerik:GridTableView>
                            </DetailTables>
                        </MasterTableView>
                    </telerik:RadGrid>
                    </telerik:RadAjaxPanel>
                </td>
            </tr>
        </table>
        <asp:HiddenField ID="hdnToday" runat="server" />
        <asp:HiddenField ID="HiddenField1" runat="server" />
        <telerik:RadCodeBlock runat="server" ID="RadCodeBlock22">
            <script type="text/javascript">
             //<![CDATA[
                function PrintRadGrid(radGridId) {
                    var radGrid = $find(radGridId);
                    var previewWnd = window.open('about:blank'''''false);
                    var sh = '<%= ClientScript.GetWebResourceUrl(gvReportUnit.GetType(),String.Format("Telerik.Web.UI.Skins.{0}.Grid.{0}.css",gvReportUnit.Skin)) %>';
                    var styleStr = "<html><head><link href = '" + sh + "' rel='stylesheet' type='text/css'></link></head>";
                    var htmlcontent = styleStr + "<body>" + radGrid.get_element().outerHTML + "</body></html>";
                    previewWnd.document.open();
                    previewWnd.document.write("<b><center>Custom Report</center></b>");
                    previewWnd.document.write(htmlcontent);
                    previewWnd.document.close();
                    previewWnd.print();
                    previewWnd.close();
                }
                function OnFromDateSelected(sender, e) {
                    var ToDate = $find("<%= txtToDate.ClientID %>");
                    if (e.get_newDate() != null) {
                        if (ToDate.get_selectedDate() != null) {
                            var ToDt = new Date(ToDate.get_selectedDate());
                            var frmDt = new Date(e.get_newDate());
                            var tsPeriod = (ToDt - frmDt) / (24 * 60 * 60 * 1000);
                            if (tsPeriod > 90) {
                                sender.clear();
                                alert('<%=  GetLocalResourceObject("msgMaxDaysLimit").ToString() %>');
                            }
                        }
                    }
                }
                function OnToDateSelected(sender, e) {
                    var fromDate = $find("<%= txtFromdate.ClientID %>");
                    if (e.get_newDate() != null) {
                        if (fromDate.get_selectedDate() != null) {
                            var frmDt = new Date(fromDate.get_selectedDate());
                            var ToDt = new Date(e.get_newDate());
                            var tsPeriod = (ToDt - frmDt) / (24 * 60 * 60 * 1000);
                            if (tsPeriod > 90) {
                                sender.clear();
                                alert('<%=  GetLocalResourceObject("msgMaxDaysLimit").ToString() %>');
                            }
                        }
                    }
                }
                function CheckChanged(objChk) {
                    var txtWeekDaysFrom = $find("<%= txtWeekDaysFrom.ClientID %>");
                    var txtWeekDaysTo = $find("<%= txtWeekDaysTo.ClientID %>");
     
                    if (objChk.checked) {
     
                        txtWeekDaysFrom.set_selectedDate(new Date('<%= Convert.ToDateTime("12:00 AM") %>'));
                        txtWeekDaysTo.set_selectedDate(new Date('<%= Convert.ToDateTime("11:59 PM") %>'));
                    }
                    else {
                        txtWeekDaysFrom.clear();
                        txtWeekDaysTo.clear();
                    }
     
                }
                function SelectionChanged(objSelected) {
                    try {
                        var list = document.getElementById('<%= rdoDayList.ClientID %>'); //Client ID of the radiolist 
                        var inputs = list.getElementsByTagName("input");
                        var selected;
                        for (var i = 0; i < inputs.length; i++) {
                            if (inputs[i].checked) {
                                selected = inputs[i];
                                break;
                            }
                        }
                        var txtFromdate = $find("<%= txtFromdate.ClientID %>");
                        var txtToDate = $find("<%= txtToDate.ClientID %>");
                        var txtWeekDaysFrom = $find("<%= txtWeekDaysFrom.ClientID %>");
                        var txtWeekDaysTo = $find("<%= txtWeekDaysTo.ClientID %>");
                        var chkFullDay = document.getElementById("<%= chkFullDay.ClientID %>");
     
                        //                      var i;
                        //                      for (i = 0; i < objSelected.cells.length; i++) {
                        //                          if (objSelected.cells[i].firstChild.checked)
                        //                              break;
                        //                      }
                        if (selected) {
                            switch (selected.value) {
                                case "None":
                                    txtFromdate.set_enabled(true);
                                    txtToDate.set_enabled(true);
                                    txtFromdate.clear();
                                    txtToDate.clear();
                                    txtWeekDaysFrom.clear();
                                    txtWeekDaysTo.clear();
                                    chkFullDay.checked = false;
                                    txtWeekDaysFrom.set_enabled(true);
                                    txtWeekDaysTo.set_enabled(true);
                                    CheckChanged(chkFullDay);
                                    break;
                                case "Today":
                                    txtFromdate.set_selectedDate(new Date('<%= DateTime.Now.Date %>'));
                                    txtToDate.set_selectedDate(new Date('<%= DateTime.Now.Date %>'));
                                    txtFromdate.set_enabled(false);
                                    txtToDate.set_enabled(false);
                                    txtWeekDaysFrom.set_enabled(true);
                                    txtWeekDaysTo.set_enabled(true);
                                    txtWeekDaysFrom.clear();
                                    txtWeekDaysTo.clear();
                                    chkFullDay.checked = false;
                                    CheckChanged(chkFullDay);
                                    break;
                                case "YesterDay":
                                    txtFromdate.set_selectedDate(new Date('<%= DateTime.Now.Date.AddDays(-1)%>'));
                                    txtToDate.set_selectedDate(new Date('<%= DateTime.Now.Date.AddDays(-1)%>'));
                                    txtFromdate.set_enabled(false);
                                    txtToDate.set_enabled(false);
                                    txtWeekDaysFrom.set_enabled(true);
                                    txtWeekDaysTo.set_enabled(true);
                                    txtWeekDaysFrom.clear();
                                    txtWeekDaysTo.clear();
                                    chkFullDay.checked = false;
                                    CheckChanged(chkFullDay);
                                    break;
                                case "ThisWeek":
     
                                    var firstDate = new Date('<%= DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek)%>');
                                    txtFromdate.set_selectedDate(firstDate);
                                    txtToDate.set_selectedDate(new Date("<%= DateTime.Now%>"));
                                    txtFromdate.set_enabled(false);
                                    txtToDate.set_enabled(false);
                                    txtWeekDaysFrom.set_enabled(false);
                                    txtWeekDaysTo.set_enabled(false);
                                    chkFullDay.checked = true;
                                    CheckChanged(chkFullDay);
                                    break;
                                case "LastWeek":
                                    txtFromdate.set_selectedDate(new Date("<%=  DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).AddDays(-7) %>"));
                                    txtToDate.set_selectedDate(new Date("<%=  DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).AddDays(-1) %>"));
                                    txtFromdate.set_enabled(false);
                                    txtToDate.set_enabled(false);
                                    txtWeekDaysFrom.set_enabled(false);
                                    txtWeekDaysTo.set_enabled(false);
                                    chkFullDay.checked = true;
                                    CheckChanged(chkFullDay);
                                    break;
                                case "Month to Date":
                                    firstDate = new Date("<%=    DateTime.Now.AddDays(-1 * (DateTime.Now.Day) + 1) %>");
                                    txtFromdate.set_selectedDate(firstDate);
                                    txtToDate.set_selectedDate(new Date("<%=  DateTime.Now %>"));
                                    txtFromdate.set_enabled(false);
                                    txtToDate.set_enabled(false);
                                    txtWeekDaysFrom.set_enabled(false);
                                    txtWeekDaysTo.set_enabled(false);
                                    chkFullDay.checked = true;
                                    CheckChanged(chkFullDay);
                                    break;
                                case "Last Month":
                                    txtFromdate.set_selectedDate(new Date(<%= DateTime.Now.AddMonths(-1).AddDays(-(int)DateTime.Now.AddMonths(-1).Day+1) %>"));
                                    txtToDate.set_selectedDate(new Date(<%= DateTime.Now.AddMonths(-1).AddDays(-(int)DateTime.Now.AddMonths(-1).Day+1).AddMonths(1).AddDays(-1) %>"));
                                    txtFromdate.set_enabled(false);
                                    txtToDate.set_enabled(false);
                                    txtWeekDaysFrom.set_enabled(false);
                                    txtWeekDaysTo.set_enabled(false);
                                    chkFullDay.checked = true;
                                    CheckChanged(chkFullDay);
                                    break;
     
                            }
                        }
                    } catch (e) {
                        txtFromdate.set_enabled(true);
                        txtToDate.set_enabled(true);
                        txtFromdate.clear();
                        txtToDate.clear();
                        txtWeekDaysFrom.clear();
                        txtWeekDaysTo.clear();
                        chkFullDay.checked = false;
                        txtWeekDaysFrom.set_enabled(true);
                        txtWeekDaysTo.set_enabled(true);
                        CheckChanged(chkFullDay);
                    }
     
                }
              //]]>
            </script>
        </telerik:RadCodeBlock>
    </asp:Content>
    
  20. Dimitrina
    Admin
    Dimitrina avatar
    3769 posts

    Posted 29 Apr 2013 Link to this post

    Hello,

    Actually this is a code library for WPF and your code is aspx code. Would you please post your question for the right category?
     

    Greetings,
    Didie
    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

  21. Ram
    Ram avatar
    2 posts
    Member since:
    May 2013

    Posted 16 Jul 2013 Link to this post

     Actually i am using the new print & print prerview method for printing when displaying radgridview in radrichtextbox i want some columns to right align & how to decrease the size of the font i have searched for a week  to find a  solution for this sill i didnt get it so suggest me how to rectify this solution.
  22. Dimitrina
    Admin
    Dimitrina avatar
    3769 posts

    Posted 16 Jul 2013 Link to this post

    Hi,

    If you follow our "Print and Export with RadDocument" demo, then the data is first exported with the GridView's Export method. To style the exported data, you can set the e.Styles dictionary with proper CSS values for text alignment and font of the cell's element when the ElementExporting is raised for the RadGridView. You can refer to the "Exporting" demo for an example.

    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 >>
  23. AEDT developer
    AEDT developer avatar
    9 posts
    Member since:
    May 2012

    Posted 26 Sep 2013 Link to this post

    Hello,

    This example works for me however it's very slow:
    1. For print dialog to show up it takes about half a minute.
    2. And actual spooling the document to printer and printing take like 10 minutes....

    My grid view data is like 40 pages long...

    Is this normal ? Do you have updated code that can speed up printing process?

    Thanks.
  24. Dimitrina
    Admin
    Dimitrina avatar
    3769 posts

    Posted 26 Sep 2013 Link to this post

    Hi,

    Please note that that printing approach is not designed for big amounts of data as the RadDocument is saved in the memory in order to be printed.

    For advanced printing scenarios I would suggest you to check the Telerik Reporting product.
     

    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 >>
  25. Rama
    Rama avatar
    2 posts
    Member since:
    Dec 2013

    Posted 23 Dec 2013 Link to this post

    can i get some example project for adding text block adding top center and bottom of  Radgridview  of Print and preview  (ex: Hello User question on this same post)


    Thanks

    Posted on Feb 9, 2013

    Hello,


    I have some questions about the latest printing project. How can I add more controls to the printing document ? For example a textblock below and above the gridview ? Also is there any way to center the content in the gridview cells and headers before printing ?

    Posted on Feb 9, 2013

    Hello,


    I have some questions about the latest printing project. How can I add more controls to the printing document ? For example a textblock below and above the gridview ? Also is there any way to center the content in the gridview cells and headers before printing ?
  26. Rama
    Rama avatar
    2 posts
    Member since:
    Dec 2013

    Posted 23 Dec 2013 Link to this post

    I have used Recent Print and Preview example for my grid i want to add a textblock at top of radgridview can i get any  example for this 


    Thanks 
    Ram
  27. Dimitrina
    Admin
    Dimitrina avatar
    3769 posts

    Posted 23 Dec 2013 Link to this post

    Hi,

    The recent printing example first exports the data using RadGridView.Export() method and then imports the exported stream to be printed. There is not an inbuilt option to export additional header above RadGridView though. You can check forum post suggesting one possible approach to additionally do this.

    Another option would be to create the document to be printed yourself. You can go through the articles about using the RadDocument and about the document viewer control - RadRichTextBox. You could as well review this article on how you could create the document elements.

    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 >>
  28. Cedric
    Cedric avatar
    2 posts
    Member since:
    Mar 2014

    Posted 18 Mar 2014 Link to this post

    Hi,
    I'm currently using vladimir extension for printing
    public static void Print(this UIElement source, string documentName) <br>{ <br>    var doc = new PrintDocument(); <br>    doc.DocumentName = documentName;    var offsetY = 0d; <br>    var totalHeight = 0d;    var canvas = new Canvas(); <br>    canvas.Children.Add(source);    doc.PrintPage += (s, e) => <br>    { <br>        e.PageVisual = canvas;        if (totalHeight == 0) <br>        { <br>            totalHeight = source.DesiredSize.Height; <br>        }        Canvas.SetTop(source, -offsetY);        offsetY += e.PrintableArea.Height; <br><br>        e.HasMorePages = offsetY <= totalHeight; <br>    }; <br><br>    doc.Print(); <br>}

    I would like to know if there is a way to add a header and footer to the printed page using this method.
    If you have a solution i would be very glad.
    Thanks for your attention.
  29. Cedric
    Cedric avatar
    2 posts
    Member since:
    Mar 2014

    Posted 18 Mar 2014 Link to this post

    Hi,
    I'm currently using vladimir extension for printing
    Here is the code i'm using:

    public static void Print(this UIElement source, string documentName)
    {
        var doc = new PrintDocument();
        doc.DocumentName = documentName;
     
        var offsetY = 0d;
        var totalHeight = 0d;
     
        var canvas = new Canvas();
        canvas.Children.Add(source);
     
        doc.PrintPage += (s, e) =>
        {
            e.PageVisual = canvas;
     
            if (totalHeight == 0)
            {
                totalHeight = source.DesiredSize.Height;
            }
     
            Canvas.SetTop(source, -offsetY);
     
            offsetY += e.PrintableArea.Height;
     
            e.HasMorePages = offsetY <= totalHeight;
        };
     
        doc.Print();
    }

    I would like to know if there is a way to add a header and footer to the printed page using this method.
    If you have a solution i would be very glad.
    Thanks for your attention.

    Sorry for the double post, i didn't encode the code right the first time, and i didn't find no edit button.
  30. Nick
    Admin
    Nick avatar
    593 posts

    Posted 21 Mar 2014 Link to this post

    Hi Cedric,

    You should be able to add any other elements to the document as in any other RadDocument. 
    This is a thread on how to add footer and headers to it

    Hope this helps.

    Regards,
    Nik
    Telerik
     

    Build cross-platform mobile apps using Visual Studio and .NET. Register for the online webinar on 03/27/2014, 11:00AM US ET.. Seats are limited.

     
Back to Top