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

Export and print RadGridView in XBAP

3 Answers 76 Views
GridView
This is a migrated thread and some comments may be shown as answers.
mariusz piatek
Top achievements
Rank 1
mariusz piatek asked on 03 Mar 2011, 08:07 AM
Is it possible to export grid data in partial trust XBAP application? I know that SaveFileDialog is not permited in partial trust, but Silverlight has his own SaveFileDialog and it works.

Next question. We want to print grid but the orginal form of print view is hopeless. There are not margins, some data is cutted, there are not title. Is it possible to override default print? We want to use the same filters and columns like in grid when print is generating.

3 Answers, 1 is accepted

Sort by
0
mariusz piatek
Top achievements
Rank 1
answered on 03 Mar 2011, 09:09 AM
Hi,
How to get cell values from gird? I can create my own print but I don't know how to get data from visible cels. I know that there is RowLoaded event but the better solution is to have reference to all formated rows.
0
mariusz piatek
Top achievements
Rank 1
answered on 04 Mar 2011, 12:58 PM
Thanks for help :/. I did my own print library.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Xps.Packaging;
using System.IO;
using System.IO.Packaging;
using System.Windows.Xps.Serialization;
 
namespace WpfApplication1
{
    /// <summary>
    /// Paper sizes
    /// A5 5.83in × 8.27in
    /// A4 8.27in × 11.69in
    /// A3 11.69in × 16.54in
    ///
    /// A5 559px × 793px
    /// A4 793px × 1055px
    ///
    /// A3 1122px × 1587px
    /// </summary>
    public enum DocumentFormat
    {
        A3,
        A4,
        A5
    }
 
    public class DocumentPaginatorWrapper : DocumentPaginator
    {
        double _fontSize = 10;
        string _topHeaderText = "Test";
        Size _pageSize;
        Size _margin;
        DocumentPaginator _paginator;
        Typeface _typeface = new Typeface("Arial");
 
 
        public DocumentPaginatorWrapper(DocumentPaginator paginator, DocumentFormat format)
        {
            switch (format)
            {
                case DocumentFormat.A3:
                    _pageSize = new Size(1122, 1587);
                    _margin = new Size(48, 48);
                    break;
                case DocumentFormat.A4:
                   // _pageSize = new Size(793, 1122);
                    _pageSize = new Size(793, 1055);
                    
                    _margin = new Size(48, 48);
                    break;
                case DocumentFormat.A5:
                    _pageSize = new Size(559, 559);
                    _margin = new Size(12, 12);
                    break;
            }
            _paginator = paginator;
            Initialize();
        }
 
        public DocumentPaginatorWrapper(DocumentPaginator paginator, DocumentFormat format , string topHeaderText, string fontTypeface, double fontSize)
        {
            _fontSize = fontSize;
            _typeface = new Typeface(fontTypeface);
            _topHeaderText = topHeaderText;
 
            switch (format)
            {
                case DocumentFormat.A3:
                    _pageSize = new Size(1122,1587);
                    _margin = new Size(48, 48);
                    break;
                case DocumentFormat.A4:
                    _pageSize = new Size(793, 1122);
                    _margin = new Size(24, 24);
                    break;
                case DocumentFormat.A5:
                    _pageSize = new Size(559, 559);
                    _margin = new Size(12, 12);
                    break;
            }
            _paginator = paginator;
            Initialize();
        }
 
        public DocumentPaginatorWrapper(DocumentPaginator paginator, Size pageSize, Size margin, string topHeaderText,string fontTypeface,double fontSize)
        {
            _fontSize = fontSize;
            _typeface = new Typeface(fontTypeface);
            _topHeaderText = topHeaderText;
            _pageSize = pageSize;
            _margin = margin;
            _paginator = paginator;
            Initialize();
        }
 
 
        public DocumentPaginatorWrapper(DocumentPaginator paginator, Size pageSize, Size margin)
        {
            _pageSize = pageSize;
            _margin = margin;
            _paginator = paginator;
            Initialize();
        }
 
 
        void Initialize()
        {
            _paginator.PageSize = new Size(_pageSize.Width - _margin.Width * 2, _pageSize.Height - _margin.Height * 2);
        }
 
 
        Rect Move(Rect rect)
        {
            if (rect.IsEmpty)
            {
                return rect;
            }
            else
            {
                return new Rect(rect.Left + _margin.Width, rect.Top + _margin.Height,
                                rect.Width, rect.Height);
            }
        }
 
        private void DrawTopHeader(DrawingContext ctx)
        {
 
            FormattedText text = new FormattedText(_topHeaderText,System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, _typeface, _fontSize , Brushes.Black);
            double textHeight = text.Height;
            ctx.DrawText(text, new Point(0, -96 / 4)); // 1/4 inch (24px) nad zawartością strony
 
            text = new FormattedText(DateTime.Now.ToString("dd-MM-yyyy  HH:mm:ss"), System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, _typeface, _fontSize, Brushes.Black);
            textHeight = text.Height;
            double textWidth = text.Width;
            ctx.DrawText(text, new Point(_pageSize.Width - 2 * _margin.Width - textWidth, -96 / 4)); // inch (24px) nad zawartością
           
            ctx.DrawLine(new Pen() { Brush = Brushes.Black }, new Point(0, -22 + textHeight), new Point(_pageSize.Width - 2 * _margin.Width, -22 + textHeight)); // linia 2px pod tekstem
        }
 
        private void DrawFooter(DrawingContext ctx, int pageNumber)
        {
            FormattedText text = new FormattedText("Strona " + (pageNumber + 1) + "/" + PageCount, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, _typeface, _fontSize, Brushes.Black);
 
            double textHeight = text.Height;
            double textWidth  = text.Width;
 
            ctx.DrawText(text, new Point(_pageSize.Width - 2 * _margin.Width - textWidth, _pageSize.Height - _margin.Height - textHeight - 24)); // inch (24px) od dołu
             
            Point p1 = new Point(0, _pageSize.Height - _margin.Height - textHeight - 26);
            Point p2 = new Point(_pageSize.Width - 2 * _margin.Width, _pageSize.Height - _margin.Height - textHeight - 26);
            ctx.DrawLine(new Pen() { Brush = Brushes.Black }, p1 , p2); // linia 2px pod tekstem
             
        }
 
        public override DocumentPage GetPage(int pageNumber)
        {
 
            DocumentPage page = _paginator.GetPage(pageNumber);
            ContainerVisual newpage = new ContainerVisual();
 
            //nagłówek
            DrawingVisual header = new DrawingVisual();
            using (DrawingContext ctx = header.RenderOpen())
            {
                DrawTopHeader(ctx);
            }
             
            //zawartość
            ContainerVisual smallerPage = new ContainerVisual();
            ContainerVisual pagina = page.Visual as ContainerVisual;
            while (pagina.Parent != null)
            {
                page.Dispose();
                _paginator.ComputePageCount();
                page = _paginator.GetPage(pageNumber);
                pagina = page.Visual as ContainerVisual;
            }
            smallerPage.Children.Add(page.Visual);
             
            //jeśli while() nie zadziała
            _paginator.ComputePageCount();
         
 
            //stopka
            DrawingVisual footer = new DrawingVisual();
            using (DrawingContext ctx = footer.RenderOpen())
            {
                 DrawFooter(ctx, pageNumber);
            }
 
            newpage.Children.Add(header);
            newpage.Children.Add(smallerPage);
            newpage.Children.Add(footer);
            newpage.Transform = new TranslateTransform(_margin.Width, _margin.Height);
 
            return new DocumentPage(newpage, _pageSize, Move(page.BleedBox), Move(page.ContentBox));
        }
 
 
      
 
 
 
        public override bool IsPageCountValid
        {
            get
            {
                return _paginator.IsPageCountValid;
            }
        }
 
 
 
        public override int PageCount
        {
            get
            {
                return _paginator.PageCount;
            }
        }
 
 
 
        public override Size PageSize
        {
            get
            {
                return _paginator.PageSize;
            }
            set
            {
                _paginator.PageSize = value;
            }
        }
        public override IDocumentPaginatorSource Source
        {
            get
            {
                return _paginator.Source;
            }
        }
    }
}

And grid extension:

using System.Windows.Documents;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Markup;
using System;
using System.Linq;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Controls;
using System.Windows.Media.Imaging;
using Telerik.Windows.Data;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Windows.Xps.Packaging;
using System.Windows.Xps.Serialization;
using WpfApplication1;
 
namespace Telerik.Windows.Printing
{
    public static class PrintExtensions
    {
 
        public static void PrintPreview(this GridViewDataControl source)
        {
            var window = new Window()
            {
                Title = "Print Preview",
                Content = Prepare(source)
            };
            window.ShowDialog();
        }
 
        private static List<GridViewBoundColumnBase> GetVisibleColumnsCollecion(this GridViewDataControl source)
        {
            List<GridViewBoundColumnBase> columns = null;
 
            columns = (from c in source.Columns.OfType<GridViewBoundColumnBase>()
                       where c.IsVisible == true
                       orderby c.DisplayIndex
                       select c).ToList<GridViewBoundColumnBase>();
 
            return columns;
        }
         
 
        public static void Print(this GridViewDataControl source, bool showDialog)
        {
            var dialog = new PrintDialog();
            var dialogResult = showDialog ? dialog.ShowDialog() : true;
 
            if (dialogResult == true)
            {
                var viewer = Prepare(source);
                dialog.PrintDocument(viewer.Document.DocumentPaginator, "");
            }
        }
 
        private static GridLength GetColumnWidth(GridViewLength length)
        {
            GridUnitType unit = GridUnitType.Auto;
 
            switch (length.UnitType)
            {
                case GridViewLengthUnitType.Pixel:
                    unit = GridUnitType.Pixel;
                    break;
                case GridViewLengthUnitType.Auto:
                    unit = GridUnitType.Auto;
                    break;
                case GridViewLengthUnitType.Star:
                    unit = GridUnitType.Star;
                    break;
            }
 
            GridLength result = new GridLength(length.Value, unit);
 
 
            return result;
        }
 
        static Paragraph CreateHeader(string text)
        {
            Run title = new Run(text);
            Paragraph pTitle = new Paragraph(title);
            pTitle.FontSize = 24;
            pTitle.FontFamily = new FontFamily("Times New Roman");
            pTitle.FontWeight = FontWeights.Bold;
            pTitle.TextAlignment = TextAlignment.Center;
            pTitle.Margin = new Thickness(15, 15, 15, 15);
            return pTitle;
        }
 
        private static XpsDocument ConvertFlowDocToXpsDoc(FlowDocument document, DocumentFormat format)
        {
            MemoryStream ms = new MemoryStream();
            Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
            string pack = "pack://report.xps";
            PackageStore.RemovePackage(new Uri(pack));
            PackageStore.AddPackage(new Uri(pack), pkg);
            XpsDocument doc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack);
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
            DocumentPaginator paginator = ((IDocumentPaginatorSource)document).DocumentPaginator;
            paginator = new DocumentPaginatorWrapper(paginator, format);
            rsm.SaveAsXaml(paginator);
            return doc;
        }
 
        private static DocumentViewer Prepare(this GridViewDataControl source)
        {
            FlowDocument oDoc = new FlowDocument();
            oDoc.ColumnWidth = 1000; //??
 
            Table oTable = new Table();
            oTable.CellSpacing = 0;
            oTable.BorderBrush = new SolidColorBrush(Colors.Black);
            oTable.BorderThickness = new Thickness(0.02);
            oDoc.Blocks.Add(CreateHeader("Testowy wydruk"));
            oDoc.Blocks.Add(oTable);
          
            TableRowGroup headerGroupRow = new TableRowGroup();
            TableRowGroup itemsGroupRow = new TableRowGroup();
 
            //styl dla nagłówka
            headerGroupRow.FontWeight = FontWeights.DemiBold;
            headerGroupRow.FontSize = 10;
            headerGroupRow.Background = new SolidColorBrush(Colors.LightGray);
            headerGroupRow.FontFamily = new FontFamily("Times New Roman");
 
            //styl dla wierszy
            itemsGroupRow.FontSize = 10;
            itemsGroupRow.FontFamily = new FontFamily("Excelsior");
            itemsGroupRow.FontWeight = FontWeights.Normal;
 
            oTable.RowGroups.Add(headerGroupRow);
            oTable.RowGroups.Add(itemsGroupRow);
 
            TableRow currentRow = null;
            TableRow headerExtraRow = null;
            string value  = string.Empty;
            List<GridViewBoundColumnBase> columns = GetVisibleColumnsCollecion(source);
 
            if (source.GroupDescriptors.Count > 0)
            {
                TableCell groupCell = new TableCell();
                Run header = new Run();
                Paragraph p = new Paragraph();
                int i = 0;
 
                header.Text = "Grupowanie : ";
                p.Inlines.Add(header);
              
                foreach (Telerik.Windows.Data.GroupDescriptor descriptor in source.GroupDescriptors)
                {
                    p.Inlines.Add(new Run() { Text = descriptor.DisplayContent.ToString()});
                    if (i++ < source.GroupDescriptors.Count - 1)
                        p.Inlines.Add(new Run() { Text = " > " });
                }
 
                groupCell.Blocks.Add(p);
                groupCell.ColumnSpan = columns.Count;
                groupCell.Background = new SolidColorBrush(Color.FromRgb(230, 230, 230));
                groupCell.Padding = new Thickness(3, 3, 3, 3);
                groupCell.BorderThickness = new Thickness(0.1);
                groupCell.BorderBrush = new SolidColorBrush(Colors.Black);
                headerExtraRow = new TableRow();
                headerExtraRow.Cells.Add(groupCell);
            }
 
 
            EventHandler<GridViewElementExportingEventArgs> elementExporting = (EventHandler<GridViewElementExportingEventArgs>)delegate(object ss, GridViewElementExportingEventArgs e)
            {
                switch (e.Element)
                {
                    case ExportElement.HeaderRow:
 
                        currentRow = new TableRow();
                        headerGroupRow.Rows.Add(currentRow);
 
                        for (int i = 0; i < columns.Count; ++i)
                        {
                            oTable.Columns.Add(new TableColumn() { Width = GetColumnWidth(columns[i].Width) });
                        }
                        if (headerExtraRow != null)
                        {
                            headerGroupRow.Rows.Add(headerExtraRow);
                        }
 
                        break;
                    case ExportElement.Row:
 
                        currentRow = new TableRow();
                        itemsGroupRow.Rows.Add(currentRow);
                        break;
 
                    case ExportElement.HeaderCell:
 
                        value = e.Value != null ? e.Value.ToString() : "";
                        TableCell headerCell = new TableCell(new Paragraph(new Run(value)));
                        headerCell.Padding = new Thickness(2);
                        headerCell.BorderBrush = new SolidColorBrush(Colors.Black);
                        headerCell.BorderThickness = new Thickness(0.1);
                        currentRow.Cells.Add(headerCell);
                        break;
                    case ExportElement.Cell:
 
                        value = e.Value != null ? e.Value.ToString() : "";
                        TableCell rowCell = new TableCell(new Paragraph(new Run(value)));
                        rowCell.Padding = new Thickness(4);
                        rowCell.BorderBrush = new SolidColorBrush(Colors.Black);
                        rowCell.BorderThickness = new Thickness(0.1);
                        currentRow.Cells.Add(rowCell);
                        break;
                        //wiersz z opisem grupowania
                    case ExportElement.GroupHeaderRow:
 
                        Telerik.Windows.Data.QueryableCollectionViewGroup groupRow = null;
                        IGroup topGroup = e.Context as IGroup;
                        List<IGroup> groupPath = new List<IGroup>();
 
                        if (topGroup != null)
                        {
                            groupPath.Add(topGroup);
 
                            if (topGroup.Subgroups.Count == 0)
                            {
                                while (topGroup.ParentGroup != null)
                                {
                                    topGroup = topGroup.ParentGroup;
                                    groupPath.Add(topGroup);
                                }
                                groupPath.Reverse();
 
                                TableCell groupCell = new TableCell();
                                Paragraph p = new Paragraph();
                                int i = 0;
                                foreach (Telerik.Windows.Data.QueryableCollectionViewGroup group in groupPath)
                                {
                                    groupRow = topGroup as Telerik.Windows.Data.QueryableCollectionViewGroup;
                                    p.Inlines.Add(new Run(group.Name.ToString()));
                                    if (i < groupPath.Count - 1)
                                        p.Inlines.Add(new Run(" > "));
                                    ++i;
                                }
                                groupCell.Blocks.Add(p);
                                groupCell.ColumnSpan = oTable.Columns.Count;
                                groupCell.Background = new SolidColorBrush(Color.FromRgb(220, 220, 220));
                                groupCell.Padding = new Thickness(3, 3, 3, 3);
                                groupCell.BorderThickness = new Thickness(0.1);
                                groupCell.BorderBrush = new SolidColorBrush(Colors.Black);
                                currentRow = new TableRow();
                                currentRow.Cells.Add(groupCell);
                                itemsGroupRow.Rows.Add(currentRow);
                            }
                        }
                        break;
                    case ExportElement.GroupHeaderCell:
                        break;
                    case ExportElement.GroupIndentCell:
                        break;
                    case ExportElement.GroupFooterRow:
                        break;
                    case ExportElement.GroupFooterCell:
                        /*
                        GridViewDataColumn column = e.Context as GridViewDataColumn;
                        AggregateFunctionsGroup group = e.Value as AggregateFunctionsGroup;
 
                        if (column != null && group != null && column.AggregateFunctions.Count() > 0)
                        {
                            AggregateResultCollection aggregateResults = group.GetAggregateResults(column.AggregateFunctions);
 
                            List<string> result = new List<string>();
                            foreach (AggregateResult r in aggregateResults)
                            {
                                if (r.FormattedValue != null)
                                {
                                    result.Add(r.FormattedValue.ToString());
                                }
                            }
                            e.Value = String.Join(",", result.ToArray());
                        }
                        */
                        break;
                }
            };
             
            MemoryStream ms = new MemoryStream();
            source.ElementExporting += elementExporting;
            source.Export(ms,
                 new GridViewExportOptions()
                 {
                     ShowColumnHeaders = true,
                     ShowColumnFooters = true,
                     ShowGroupFooters = true,
                 });
            source.ElementExporting -= elementExporting;
 
            XpsDocument xpsDoc = ConvertFlowDocToXpsDoc(oDoc, DocumentFormat.A4);
            var viewer = new DocumentViewer();
            viewer.Document = xpsDoc.GetFixedDocumentSequence();
 
            return viewer;
        }
    }
}


Please check it if there are bugs.
0
band
Top achievements
Rank 1
answered on 06 Apr 2017, 07:41 PM
Solution works very well, is there a way to repeat column headers?
Tags
GridView
Asked by
mariusz piatek
Top achievements
Rank 1
Answers by
mariusz piatek
Top achievements
Rank 1
band
Top achievements
Rank 1
Share this question
or