New to Telerik UI for WinForms? Download free 30-day trial

Export to PDF

Overview

RadGridView can export its contents to PDF using two separate mechanisms.

  • The GridViewPdfExport object utilizes the powerful RadPdfProcessing library and exports RadGridView`s data natively to the PDF format.

  • The ExportToPdf object on the other hand first renders RadGridView as an XHTML table and the export process will convert that table to a PDF document. That said, Export to PDF supports all of the ExportToHTML settings, but it also adds some PDF specific ones.

Exporting Data using GridViewPdfExport object

The GridViewPdfExport functionality is located in the TelerikExport.dll assembly. You need to include the following namespace in order to access the types contained in TelerikExport :

  • Telerik.WinControls.Export

The ExportToPdf functionality is located in the TelerikData.dll assembly. You need to include the following namespace in order to access the types contained in TelerikData :

  • Telerik.WinControls.UI.Export

Initialization

Before running export to PDF, you have to initialize the GridViewPdfExport class. The constructor takes one parameter: RadGridView which will be exported:

GridViewPdfExport initialization


Telerik.WinControls.Export.GridViewPdfExport pdfExporter = new Telerik.WinControls.Export.GridViewPdfExport(this.radGridView1);

Dim pdfExporter As New Telerik.WinControls.Export.GridViewPdfExport(Me.RadGridView1)

File Extension

The FileExtension property allows you to change the default (*.pdf) file extension of the exported file:

Setting the file extension


pdfExporter.FileExtension = ".pdf";

pdfExporter.FileExtension = ".pdf"

Hidden columns and rows option

GridViewPdfExport uses the default enumeration of hidden column and row settings. You can choose one of the three options by setting HiddenColumnOption and HiddenRowOption properties. However, PDF do not support real hidden columns, so choosing the ExportAsHidden will not behave the same as ExportAlways.

  • ExportAlways

  • DoNotExport (default)

  • ExportAsHidden (brings the same result as ExportAlways option)

Setting the HiddenColumnOption


pdfExporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;

pdfExporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport

Before applying customizations to the headers and footers we need to enable them:

Enabling headers and footers


pdfExporter.ShowHeaderAndFooter = true;

pdfExporter.ShowHeaderAndFooter = True

Customizing headers and footers


pdfExporter.HeaderHeight = 30;
pdfExporter.HeaderFont = new Font("Arial", 22);
pdfExporter.Logo = System.Drawing.Image.FromFile(@"C:\MyLogo.png");
pdfExporter.LeftHeader = "[Logo]";
pdfExporter.LogoAlignment = ContentAlignment.MiddleLeft;
pdfExporter.LogoLayout = Telerik.WinControls.Export.LogoLayout.Fit;

pdfExporter.MiddleHeader = "Middle header";
pdfExporter.RightHeader = "Right header";
pdfExporter.ReverseHeaderOnEvenPages = true;

pdfExporter.FooterHeight = 30;
pdfExporter.FooterFont = new Font("Arial", 22);
pdfExporter.LeftFooter = "Left footer";
pdfExporter.MiddleFooter = "Middle footer";
pdfExporter.RightFooter = "Right footer";
pdfExporter.ReverseFooterOnEvenPages = true;

pdfExporter.HeaderHeight = 30
pdfExporter.HeaderFont = New Font("Arial", 22)
pdfExporter.Logo = System.Drawing.Image.FromFile("C:\MyLogo.png")
pdfExporter.LeftHeader = "[Logo]"
pdfExporter.LogoAlignment = ContentAlignment.MiddleLeft
pdfExporter.LogoLayout = Telerik.WinControls.Export.LogoLayout.Fit
pdfExporter.MiddleHeader = "Middle header"
pdfExporter.RightHeader = "Right header"
pdfExporter.ReverseHeaderOnEvenPages = True
pdfExporter.FooterHeight = 30
pdfExporter.FooterFont = New Font("Arial", 22)
pdfExporter.LeftFooter = "Left footer"
pdfExporter.MiddleFooter = "Middle footer"
pdfExporter.RightFooter = "Right footer"
pdfExporter.ReverseFooterOnEvenPages = True

The HeaderExported event can be used to perform custom drawing in the header. The following example shows how you can draw a two line header.

Using the HeaderExported event

Summaries export option

The SummariesExportOption property to specifies how to export summary items. There are four options to choose:

  • ExportAll (default)

  • ExportOnlyTop

  • ExportOnlyBottom

  • DoNotExport

Setting summary items


pdfExporter.SummariesExportOption = SummariesOption.ExportAll;

pdfExporter.SummariesExportOption = SummariesOption.ExportAll

Fit to page

Use this property to make the grid fits to the PDF page width.

Setting FitToPageWidth


pdfExporter.FitToPageWidth = true;

pdfExporter.FitToPageWidth = True

Scale

You can use Scale to change the grid size on the PDF. For example if Scale = 1.2f means the grid will be 20% bigger.

Setting scale


pdfExporter.Scale = 1.2;

pdfExporter.Scale = 1.2

PDF Export Settings

The PDFExportSettings property supports various settings on PDF file level. You can set the following:

  • Author

  • Title

  • Description

Using export settings


pdfExporter.ExportSettings.Description = "Document Description";

pdfExporter.ExportSettings.Description = "Document Description"

ExportViewDefinition

Gets or sets a value indicating whether to export the view definition.

ChildViewExportMode: Defines which child view of a hierarchy row to be exported. Available modes are:

  • ExportFirstView: The exporter exports the first view.

  • ExportCurrentlyActiveView: The exporter exports the view that is active in the grid.

  • ExportAllViews: All child views are exported.

  • SelectViewToExport: In this mode the ChildViewExporing event is fired. The event allows to choose the view to export in row by row basis.

PDF Export Settings

The PDFExportSettings property supports various settings on PDF file level. You can set the following:

  • Author

  • Title

  • Description

Using export settings


pdfExporter.ExportSettings.Description = "Document Description";

pdfExporter.ExportSettings.Description = "Document Description"

Exporting to PDF

Two methods are responsible for exporting data to PDF. Both receive as a parameter the file name.

  • RunExport: Runs synchronously.

Running export


string fileName = "c:\\ExportedData.pdf";
pdfExporter.RunExport(fileName, new Telerik.WinControls.Export.PdfExportRenderer());

Dim fileName As String = "c:\ExportedData.pdf"
pdfExporter.RunExport(fileName, New Telerik.WinControls.Export.PdfExportRenderer())

The RunExport method has several overloads allowing the user to export using a stream as well:

Running export synchronously using a stream


string exportFile = @"..\..\exportedData.pdf";
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
    Telerik.WinControls.Export.GridViewPdfExport exporter = new Telerik.WinControls.Export.GridViewPdfExport(this.radGridView1);
    Telerik.WinControls.Export.PdfExportRenderer renderer = new Telerik.WinControls.Export.PdfExportRenderer();
    exporter.RunExport(ms, renderer);

    using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write))
    {
        ms.WriteTo(fileStream);
    }
}

Dim exportFile As String = "..\..\exportedData.pdf"
Using ms As New System.IO.MemoryStream()
    Dim exporter As New Telerik.WinControls.Export.GridViewPdfExport(Me.RadGridView1)
    Dim renderer As New Telerik.WinControls.Export.PdfExportRenderer()
    exporter.RunExport(ms, renderer)
    Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)
        ms.WriteTo(fileStream)
    End Using
End Using

  • RunExportAsync: Runs on a thread different than the UI thread.

Running export asynchronously


string fileNameAsync = "c:\\ExportedDataAsync.pdf";
pdfExporter.RunExportAsync(fileNameAsync, new Telerik.WinControls.Export.PdfExportRenderer());

Dim fileNameAsync As String = "c:\ExportedDataAsync.pdf"
pdfExporter.RunExportAsync(fileNameAsync, New Telerik.WinControls.Export.PdfExportRenderer())

The RunExportAsync method has several overloads allowing the user to export using a stream as well:


private void radButton1_Click(object sender, EventArgs e)
{
    System.IO.MemoryStream ms = new System.IO.MemoryStream();         
    Telerik.WinControls.Export.GridViewPdfExport pdfExporter = new Telerik.WinControls.Export.GridViewPdfExport(this.radGridView1);
    Telerik.WinControls.Export.PdfExportRenderer renderer = new Telerik.WinControls.Export.PdfExportRenderer();
    pdfExporter.AsyncExportCompleted += pdfExporter_AsyncExportCompleted;
    pdfExporter.RunExportAsync(ms, renderer);
}

private void pdfExporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e)
{
    RunWorkerCompletedEventArgs args = e as RunWorkerCompletedEventArgs;
    string exportFile = @"..\..\exportedAsyncData.pdf";
    using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write))
    { 
        MemoryStream ms = args.Result as MemoryStream;
        ms.WriteTo(fileStream);
        ms.Close();
    }
}

Private Sub radButton1_Click(sender As Object, e As EventArgs)
    Dim ms As New System.IO.MemoryStream()
    Dim pdfExporter As New Telerik.WinControls.Export.GridViewPdfExport(Me.RadGridView1)
    Dim renderer As New Telerik.WinControls.Export.PdfExportRenderer()
    AddHandler pdfExporter.AsyncExportCompleted, AddressOf pdfExporter_AsyncExportCompleted
    pdfExporter.RunExportAsync(ms, renderer)
End Sub
Private Sub pdfExporter_AsyncExportCompleted(sender As Object, e As AsyncCompletedEventArgs)
    Dim args As RunWorkerCompletedEventArgs = TryCast(e, RunWorkerCompletedEventArgs)
    Dim exportFile As String = "..\..\exportedAsyncData.pdf"
    Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)
        Dim ms As MemoryStream = TryCast(args.Result, MemoryStream)
        ms.WriteTo(fileStream)
        ms.Close()
    End Using
End Sub

Events

  • CellFormatting: Fires for every cell which is being exported

  • CellPaint: Fires when a cell is being drawn

Exporting Data using ExportToPDF object

Initialization

Before running export to PDF, you have to initialize the ExportToPDF class. The constructor takes one parameter: RadGridView which will be exported:

ExportToPDF initialization

ExportToPDF exporter = new ExportToPDF(this.radGridView1);

Dim exporter As New ExportToPDF(Me.RadGridView1)

File Extension

The FileExtension property allows you to change the default (*.pdf) file extension of the exported file:

Setting the FileExtension

exporter.FileExtension = "pdf";

exporter.FileExtension = "pdf"

Hidden columns and rows option

ExportToPDF uses the default enumeration of hidden column and row settings. You can choose one of the three options by setting HiddenColumnOption and HiddenRowOption properties. However, PDF do not support real hidden columns, so choosing the ExportAsHidden will not behave the same as ExportAlways.

  • ExportAlways

  • DoNotExport (default)

  • ExportAsHidden  (brings the same result as ExportAlways option)

Setting the HiddenColumnOption

exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;

exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport

Exporting Visual Settings

Using the ExportToPDF class allows you to export the visual settings (themes) to the PDF file. ExportToPDF also provides a visual representation of the alternating row color. This feature works only if EnableAlternatingRow property is set to true. Note that it does not transfer the alternating row settings that come from the theme of the control. RadGridView will also export the conditional formatting to the PDF file. You can enable exporting visual settings through the ExportVisualSettings property. The default value of this property is false.

Setting the ExportVisualSettings

exporter.ExportVisualSettings = true;

exporter.ExportVisualSettings = True

Page Title

You can add a page title which will be presented on every page of the PDF document through __PageTitle__property.

Setting the PageTitle

exporter.PageTitle = "Title";

exporter.PageTitle = "Title"

Summaries export option

You can use SummariesExportOption property to specify how to export summary items. There are four options to choose:

  • ExportAll (default)

  • ExportOnlyTop

  • ExportOnlyBottom

  • DoNotExport

Setting the SummariesExportOption

exporter.SummariesExportOption = SummariesOption.ExportAll;

exporter.SummariesExportOption = SummariesOption.ExportAll

Fit to page

Use this property to make the grid fits to the PDF page width.

Setting the FitToPageWidth

exporter.FitToPageWidth = true;

exporter.FitToPageWidth = True

Scale

You can use Scale to change the grid size on the PDF. For example if Scale = 1.2f means the grid will be 20% bigger.

Setting the Scale

exporter.Scale = 1.2f;

exporter.Scale = 1.2F

TableBorderThickness

This property controls the thickness of the table border. The default value is 0 and border is not drawn.

Setting the TableBorderTickness

exporter.TableBorderThickness = 1;

exporter.TableBorderThickness = 1

PDF Export Settings

The PDFExportSettings property supports various settings on PDF file level. You can set the following:

  • Author

  • Creator

  • EnableAdd

  • EnableCopy

  • EnableModify

  • EnablePrinting

  • FontType

  • Keywords

  • Page Margins: PageBottomMargin, PageTopMargin, PageLeftMargin, PageRightMargin, PageFooterMargin

  • Page Size: PageHeight and PageWidth

  • Producer

  • Subject

  • Title

Setting the PDFDocumentSettings

exporter.PdfExportSettings.PageHeight = 210;
exporter.PdfExportSettings.PageWidth = 297;

exporter.PdfExportSettings.PageHeight = 210
        exporter.PdfExportSettings.PageWidth = 297

RunExport method

Exporting data to PDF is done through the RunExport method of ExportToPDF object. The RunExport method accepts the following parameter:

  • fileName - the name of the exported file

Consider the code sample below:

Exporting to PDF format

string fileName = "c:\\ExportedData.pdf";
exporter.RunExport(fileName);

Dim fileName As String = "c:\ExportedData.pdf"
        exporter.RunExport(fileName)

Events

HTMLCellFormating event: Since the the export process first renders RadGridView in XHTML format you can use the event which comes from ExportToHTML class: HTMLCellFormatting. It gives access to a single cell  HTML element that allows you to make additional formatting for every HTML cell related to the exported RadGridView:

Handling the HTMLCellFormatting event

void exporter_HTMLCellFormatting(object sender, Telerik.WinControls.UI.Export.HTML.HTMLCellFormattingEventArgs e)
{
    if (e.GridColumnIndex == 1 && e.GridRowInfoType == typeof(GridViewDataRowInfo))
    {
        e.HTMLCellElement.Value = "Test value";
        e.HTMLCellElement.Styles.Add("background-color", ColorTranslator.ToHtml(Color.Orange));
    }
}

Private Sub exporter_HTMLCellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.HTML.HTMLCellFormattingEventArgs)
        If e.GridColumnIndex = 1 AndAlso e.GridRowInfoType.Equals(GetType(GridViewDataRowInfo)) Then
            e.HTMLCellElement.Value = "Test value"
            e.HTMLCellElement.Styles.Add("background-color", ColorTranslator.ToHtml(Color.Orange))
        End If
    End Sub

Fonts / Unicode support

ExportToPDF supports all left-to-right languages when the appropriate Unicode font is set. The most common international font is Arial Unicode MS, because it covers all Unicode characters. Of course, you can use other-specific fonts such as Batang for Korean, SimSun for Chinese, MS Mincho for Japanese, etc.

void pdfExporter_HTMLCellFormatting(object sender, HTMLCellFormattingEventArgs e)
{
    //The following sets unicode font for every cell.  
    e.HTMLCellElement.Styles.Remove("font-family");
    e.HTMLCellElement.Styles.Add("font-family", "Arial Unicode MS");
}

Private Sub pdfExporter_HTMLCellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.HTML.HTMLCellFormattingEventArgs)
    'The following sets unicode font for every cell.  
    e.HTMLCellElement.Styles.Remove("font-family")
    e.HTMLCellElement.Styles.Add("font-family", "Arial Unicode MS")
End Sub

See Also

In this article