Back to Devexpress

DxGrid.ExportToPdfAsync(String, GridPdfExportOptions) Method

blazor-devexpress-dot-blazor-dot-dxgrid-dot-exporttopdfasync-x28-system-dot-string-devexpress-dot-blazor-dot-gridpdfexportoptions-x29.md

latest9.2 KB
Original Source

DxGrid.ExportToPdfAsync(String, GridPdfExportOptions) Method

Exports Grid data to PDF and downloads the output file onto the client machine.

Namespace : DevExpress.Blazor

Assembly : DevExpress.Blazor.v25.2.dll

NuGet Package : DevExpress.Blazor

Declaration

csharp
public Task ExportToPdfAsync(
    string fileName,
    GridPdfExportOptions options = null
)

Parameters

NameTypeDescription
fileNameString

The file name.

|

Optional Parameters

NameTypeDefaultDescription
optionsGridPdfExportOptionsnull

PDF export options.

|

Returns

TypeDescription
Task

The task that is completed when the file is downloaded.

|

Remarks

Call the ExportToPdfAsync method to export Grid data to PDF. Method overloads allow you to write the result to a stream (ExportToPdfAsync(Stream, GridPdfExportOptions)) or to a file downloaded onto a client machine (the current overload).

The method accepts a GridPdfExportOptions object as a parameter. Use this parameter to configure export settings.

Run Demo: Grid - Export Read Tutorial: Export to PDF

Example

The following example exports selected rows to PDF and customizes the output document’s appearance:

razor
@rendermode InteractiveServer
@using DevExpress.Drawing;
@inject WeatherForecastService ForecastService

<DxGrid @ref="Grid" Data="@forecasts">
    <Columns>
        <DxGridSelectionColumn Width="60px" AllowSelectAll="true" />
        <DxGridDataColumn Caption="Date" FieldName="Date" />
        <DxGridDataColumn Caption="Temperature (C)" FieldName="TemperatureC" />
        <DxGridDataColumn Caption="Temperature (F)" FieldName="TemperatureF" />
        <DxGridDataColumn Caption="Summary" FieldName="Summary" />
    </Columns>
    <ToolbarTemplate>
        <DxToolbar>
            <DxToolbarItem Text="Export to PDF" Click="ExportPdf_Click" BeginGroup="true" />
        </DxToolbar>
    </ToolbarTemplate>
</DxGrid>

@code {
    IGrid Grid;
    private WeatherForecast[]? forecasts;

    protected override async Task OnInitializedAsync() {
        forecasts = await ForecastService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now));
    }
    async Task ExportPdf_Click() {
        await Grid.ExportToPdfAsync("ExportResult", new GridPdfExportOptions() {
            ExportSelectedRowsOnly = true, // Exports only selected rows
            CustomizeCell = OnCustomizeCell, // Customizes table cell appearance
            CustomizeDocument = OnCustomizeDocument, // Customizes overall document appearance
            CustomizeDocumentHeader = OnCustomizeDocumentHeader, // Adds and customizes a document header
        });
    }
    void OnCustomizeDocument(GridDocumentExportCustomizeDocumentEventArgs args) {
        // Sets default font settings for all elements
        args.DefaultElementStyle.Font = new DXFont("Times New Roman", 12, DXFontStyle.Regular);
        // Switches the page orientation to landscape
        args.Landscape = true;
    }
    void OnCustomizeCell(GridDocumentExportCustomizeCellEventArgs args) {
        // Sets border settings for all table cells
        args.ElementStyle.BorderColor = System.Drawing.Color.DarkGray;
        args.ElementStyle.BorderDashStyle = DevExpress.XtraPrinting.BorderDashStyle.Dash;
        // Sets style settings for header cells
        if (args.AreaType == DocumentExportAreaType.Header) {
            args.ElementStyle.BackColor = System.Drawing.Color.LightGray;
            args.ElementStyle.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
            args.ElementStyle.Font = new DXFont("Arial", 12, DXFontStyle.Bold);
        }
        args.Handled = true;
    }
    void OnCustomizeDocumentHeader(GridDocumentExportCustomizeDocumentHeaderFooterEventArgs args) {
        // Adds a document header
        args.Text = "Weather Forecast";
        // Sets header style settings
        args.ElementStyle.Font = new DXFont("Arial", 12, DXFontStyle.Regular);
        args.ElementStyle.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
    }
}
csharp
using System;

public class WeatherForecast {
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public string Forecast { get; set; }
    public string CloudCover { get; set; }
}
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

public class WeatherForecastService {
    private List<WeatherForecast> Forecast { get; set; }

    private static string[] CloudCover = new[] {
        "Sunny", "Partly cloudy", "Cloudy", "Storm"
    };

    Tuple<int, string>[] ConditionsForForecast = new Tuple<int, string>[] {
        Tuple.Create( 22 , "Hot"),
        Tuple.Create( 13 , "Warm"),
        Tuple.Create( 0 , "Cold"),
        Tuple.Create( -10 , "Freezing")
    };

    public WeatherForecastService() {
        Forecast = CreateForecast();
    }

    private List<WeatherForecast> CreateForecast() {
        var rng = new Random();
        DateTime startDate = DateTime.Now;
        return Enumerable.Range(1, 30).Select(index => {
            var temperatureC = rng.Next(-10, 30);
            return new WeatherForecast {
                Date = startDate.AddDays(index),
                TemperatureC = temperatureC,
                CloudCover = CloudCover[rng.Next(0, 4)],
                Forecast = ConditionsForForecast.First(c => c.Item1 <= temperatureC).Item2
            };
        }).ToList();
    }

    public List<WeatherForecast> GetForecast() {
        return Forecast;
    }

    public Task<WeatherForecast[]> GetForecastAsync(CancellationToken ct = default) {
        return Task.FromResult(Forecast.ToArray());
    }
}
csharp
// ...
builder.Services.AddSingleton<WeatherForecastService>();

Prerequisites

Blazor WebAssembly AppsPDF export in WebAssembly applications has the following prerequisites:

Blazor Server Apps

  • For non-Windows environments (Linux, macOS, and Azure/AWS cloud platforms), install the DevExpress.Drawing.Skia NuGet package.

  • On Linux, you must also install the following font libraries:

Limitations and Specifics

  • Template content is not exported (including detail Grids).
  • CSS classes applied to the Grid and its elements do not affect the exported document’s appearance. Handle the CustomizeCell event to customize the output table.
  • The Grid does not export columns whose Visible property is set to false. Handle the CustomizeColumn event to add hidden columns to the output file.
  • The Grid exports all data rows that match the current filter criteria (including rows in collapsed groups). Handle the RowExporting event to exclude specific rows from export.
  • When the Grid is bound to a GridDevExtremeDataSource, you must specify the KeyFieldName property to export only selected rows.

Implements

ExportToPdfAsync(String, GridPdfExportOptions)

See Also

DxGrid Class

DxGrid Members

DevExpress.Blazor Namespace