Skip to main content Skip to footer

Export C1FlexGrid to PDF

C1Flexgrid for WPF provides lot of flexibility in terms of exporting the data to various formats. PDF Export technique depends on the following two important things :

  1. GetPageImages method of C1Flexgrid

  2. Page Template

GetPageImages method returns a list of images that represent a paged view of the grid. These images can then be added to a collection and rendered to the PDF page. Page Template defines the layout of the Page to be rendered in the exported PDF. Following Code snippet defines the PDF Export:

// export the grid to a PDF file  
 void SavePdf(Stream s, string documentName)  
 {  
     // get root element to lay out the PDF pages  
     Panel root = null;  
    for (var parent = c1Flexgrid1.Parent as FrameworkElement; parent != null; parent = parent.Parent as FrameworkElement)  
     {  
         if (parent is Panel)  
         {  
             root = parent as Panel;  
         }  
     }  
     // create pdf document  
     var pdf = new C1PdfDocument(PaperKind.Letter, false);  
     // get page size  
     var rc = pdf.PageRectangle;  
     var m = new Thickness(96, 96, 96 / 2, 96 / 2);  
     var scaleMode = ScaleMode.ActualSize;  
     // create panel to hold elements while they render  
     var pageTemplate = new PageTemplate();  
     pageTemplate.Width = rc.Width;  
     pageTemplate.Height = rc.Height;  
     pageTemplate.SetPageMargin(m);  
     root.Children.Add(pageTemplate);  
     // render grid into PDF document  
     var sz = new Size(rc.Width - m.Left - m.Right, rc.Height - m.Top - m.Bottom);  
     var pages = c1Flexgrid1.GetPageImages(scaleMode, sz, 100);  
     for (int i = 0; i < pages.Count; i++)  
     {  
         // skip a page when necessary  
         if (i > 0)  
         {  
             pdf.NewPage();  
         }  
         // set content  
         pageTemplate.PageContent.Child = pages[i];  
         //pageTemplate.PageContent.Stretch = System.Windows.Media.Stretch.Uniform;  
         pageTemplate.PageContent.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;  
         // set header/footer text  
         //pageTemplate.HeaderLeft.Text = documentName;  
         pageTemplate.FooterRight.Text = string.Format("Page {0} of {1}",  
         i + 1, pages.Count);  
         // measure page element  
         pageTemplate.Measure(new Size(rc.Width, rc.Height));  
         pageTemplate.UpdateLayout();  
         // add page element to PDF  
         pdf.DrawElement(pageTemplate, rc);  
     }  
     // done with template  
     root.Children.Remove(pageTemplate);  
     // save the PDF document  
     pdf.Save(s);  
     s.Close();  
 }