Create or Generate PDF document in Blazor
29 Jul 202624 minutes to read
The .NET PDF library is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, work with forms, and secure PDF documents.
To include the Syncfusion® .NET PDF library into your Blazor application, please refer to the NuGet Package Required or Assemblies Required documentation.
To quickly get started with creating a PDF document in Blazor, check this video:
Steps to create a PDF document in Blazor Server application
Prerequisites:
- Install the .NET SDK on your machine. The latest version can be downloaded from the .NET Downloads page.
- Set up your development environment by installing Visual Studio from the official Visual Studio website.
Step 1: Create a new C# Blazor server-side application project. Select Blazor Web App from the template and click the Next button.

Step 2: In the Interactive Render Mode section, choose Server as the render mode. Then, click the Create button to generate a new Blazor Server-Side Application.

Step 3: To create a PDF document in a Blazor Server app, install the Syncfusion.PDF.Net.Core package into your Blazor project.

Step 4: Register the Syncfusion® license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in Program.cs before initializing any Syncfusion® component:
using Syncfusion.Licensing;
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
var app = builder.Build();Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 5: Create a new cs file named ExportService.cs under the Data folder and include the following namespaces and class declaration in the file.
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
using Syncfusion.Drawing;Step 6: The PdfDocument object represents an entire PDF document that is being created. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data sources.
Add the following code sample in the ExportService class which illustrates how to create a simple PDF document using PdfTextElement and PdfGrid.
//Export weather data to PDF document.
public static MemoryStream CreatePdf(WeatherForecast[] forecasts)
{
if (forecasts == null)
{
throw new ArgumentNullException("Forecast cannot be null");
}
//Create a new PDF document.
using (PdfDocument pdfDocument = new PdfDocument())
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Add page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a service and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid.
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
using (MemoryStream stream = new MemoryStream())
{
//Saving the PDF document into the stream.
pdfDocument.Save(stream);
//Closing the PDF document.
pdfDocument.Close(true);
return stream;
}
}
}Step 7: Register your service in the Program.cs class as follows.
using BlazorServerApp.Data;
// ...
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddSingleton<ExportService>();Step 8: Inject ExportService into Weather.razor using the following code.
@inject ExportService ExportService
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.IOCreate a button in the Weather.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Add the ExportToPdf method in the Weather.razor page to call the export service.
@functions
{
protected async Task ExportToPdf()
{
using (MemoryStream pdfStream = ExportService.CreatePdf(forecasts))
{
await JS.SaveAs("Sample.pdf", pdfStream.ToArray());
}
}
}Step 9: Include the FileUtil class within the ExportService.cs file to enable file-related operations as part of the export functionality.
public static class FileUtil
{
public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}Step 10: Add the following JavaScript function in the App.razor file available under the Components folder.
<script type = "text/javascript" >
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob)
{
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>Step 11: Build the project.
Click on Build → Build Solution or press Ctrl+Shift+B to build the project.
Step 12: Run the project.
Click the Start button (green arrow) or press F5 to run the app.
Prerequisites:
- Install .NET SDK: Ensure that you have the .NET SDK installed on your system. You can download it from the .NET Downloads page.
- Install Visual Studio Code: Download and install Visual Studio Code from the official website.
- Install C# Extension for VS Code: Open Visual Studio Code, go to the Extensions view (Ctrl+Shift+X), and search for ‘C#’. Install the official C# extension provided by Microsoft.
Step 1: Open the terminal (Ctrl+` ) and run the following command to create a new Blazor Web App (Server) application.
dotnet new blazorserver -n CreatePdfBlazorServerApp
Step 2: Replace CreatePdfBlazorServerApp with your desired project name.
Step 3: Navigate to the project directory using the following command
cd CreatePdfBlazorServerApp
Step 4: Use the following command in the terminal to add the Syncfusion.Pdf.Net.Core package to your project.
dotnet add package Syncfusion.Pdf.Net.Core
Step 5: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in Program.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
var app = builder.Build();Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 6: Create a new cs file named ExportService.cs under the Data folder and include the following namespaces and class declaration in the file.
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
using Syncfusion.Drawing;Step 7: The PdfDocument object represents an entire PDF document that is being created. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data sources.
Add the following code sample in the ExportService class which illustrates how to create a simple PDF document using PdfTextElement and PdfGrid.
//Export weather data to PDF document.
public static MemoryStream CreatePdf(WeatherForecast[] forecasts)
{
if (forecasts == null)
{
throw new ArgumentNullException("Forecast cannot be null");
}
//Create a new PDF document.
using (PdfDocument pdfDocument = new PdfDocument())
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Add page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a service and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid.
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
using (MemoryStream stream = new MemoryStream())
{
//Saving the PDF document into the stream.
pdfDocument.Save(stream);
//Closing the PDF document.
pdfDocument.Close(true);
return stream;
}
}
}Step 8: Register your service in the Program.cs class as follows.
using CreatePdfBlazorServerApp.Data;
// ...
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddSingleton<ExportService>();Step 9: Inject ExportService into FetchData.razor using the following code.
@inject ExportService ExportService
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.IOCreate a button in the FetchData.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Add the ExportToPdf method in the FetchData.razor page to call the export service.
@functions
{
protected async Task ExportToPdf()
{
using (MemoryStream pdfStream = ExportService.CreatePdf(forecasts))
{
await JS.SaveAs("Sample.pdf", pdfStream.ToArray());
}
}
}Step 10: Create a class file named FileUtil.cs and add the following code to invoke the JavaScript action to download the file in the browser.
public static class FileUtil
{
public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}Step 11: Add the following JavaScript function in the App.razor file available under the Components folder.
<script type = "text/javascript" >
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob)
{
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>Step 12: Build the project.
Run the following command in terminal to build the project.
dotnet build
Step 13: Run the project.
Run the following command in the terminal to run the project.
dotnet run
Prerequisites:
- JetBrains Rider.
- Install .NET 8 SDK or later.
Step 1. Open JetBrains Rider and create a new Blazor server-side app project.
- Launch JetBrains Rider.
- Click new solution on the welcome screen.

- In the new Solution dialog, select Project Type as Web.
- Enter a project name and specify the location.
- Choose template as Blazor Server App.
- Select the target framework (e.g., .NET 8.0, .NET 9.0).
- Click create.

Step 2: Install the NuGet package from NuGet.org.
- Click the NuGet icon in the Rider toolbar and type Syncfusion.Pdf.Net.Core in the search bar.
- Ensure that “nuget.org” is selected as the package source.
- Select the latest Syncfusion.Pdf.Net.Core NuGet package from the list.
- Click the + (Add) button to add the package.

- Click the Install button to complete the installation.

Step 3: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in Program.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
var app = builder.Build();Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 4: Create a new cs file named ExportService.cs under Data folder and include the following namespaces and class declaration in the file.
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
using Syncfusion.Drawing;Step 5: The PdfDocument object represents an entire PDF document that is being created. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data sources.
Add the following code sample in the ExportService class which illustrates how to create a simple PDF document using PdfTextElement and PdfGrid.
//Export weather data to PDF document.
public static MemoryStream CreatePdf(WeatherForecast[] forecasts)
{
if (forecasts == null)
{
throw new ArgumentNullException("Forecast cannot be null");
}
//Create a new PDF document.
using (PdfDocument pdfDocument = new PdfDocument())
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Add page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a service and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid.
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
using (MemoryStream stream = new MemoryStream())
{
//Saving the PDF document into the stream.
pdfDocument.Save(stream);
//Closing the PDF document.
pdfDocument.Close(true);
return stream;
}
}
}Register your service in the Program.cs class as follows.
using BlazorServerApp.Data;
// ...
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddSingleton<ExportService>();Step 6: Inject ExportService into FetchData.razor using the following code.
@inject ExportService ExportService
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.IOCreate a button in the FetchData.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Add the ExportToPdf method in the FetchData.razor page to call the export service.
@functions
{
protected async Task ExportToPdf()
{
using (MemoryStream pdfStream = ExportService.CreatePdf(forecasts))
{
await JS.SaveAs("Sample.pdf", pdfStream.ToArray());
}
}
}Step 7: Create a class file named FileUtil.cs and add the following code to invoke the JavaScript action to download the file in the browser.
public static class FileUtil
{
public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}Step 8: Add the following JavaScript function in the App.razor file available under the Components folder.
<script type = "text/javascript" >
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob)
{
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>Step 9: Build the project.
Click the Build button in the toolbar or press Ctrl+Shift+B to build the project.
Step 10: Run the project.
Click the Run button (green arrow) in the toolbar or press Shift+F10 to run the app.
You can download a complete working sample from GitHub.
By executing the program, you will get the following output in the browser.

Click the Export to PDF button to get the PDF document with the following output.

NOTE
We recommend using Blazor Server (server-side) applications. They reduce the payload sent to the client and improve performance compared to Blazor WebAssembly (client-side) applications.
Steps to create a PDF document in Blazor WebAssembly application
Prerequisites:
- Install .NET SDK: Ensure that you have the .NET SDK installed on your system. You can download it from the .NET Downloads page.
- Install Visual Studio: Download and install Visual Studio from the official website.
Step 1: Create a new C# Blazor client-side application project. Select Blazor Web App from the template and click the Next button.

Step 2: In the Interactive Render Mode section, choose WebAssembly as the render mode. Then, click the Create button to generate a new Blazor client-Side Application.

Step 3: Install the Syncfusion.PDF.Net.Core NuGet package as a reference to your Blazor application from NuGet.org.

Step 4: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in Program.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
var app = builder.Build();Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 5: Next, include the following namespaces in the FetchData.razor file.
@using Syncfusion.Pdf
@using Syncfusion.Pdf.Grid
@using Syncfusion.Drawing
@using Syncfusion.Pdf.Graphics
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.IOStep 5: Create a button in the FetchData.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Step 7: Define the @ExportToPdf click function on the FetchData.razor file.
The PdfDocument object represents an entire PDF document that is being created and add a PdfPage to it. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data sources.
@functions {
void ExportToPdf()
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
//Add Page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
//Create text element.
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a client side and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
//Create memory stream.
MemoryStream memoryStream = new MemoryStream();
//Save the PDF document.
pdfDocument.Save(memoryStream);
//Close the PDF document
pdfDocument.Close(true);
//Download the PDF document
JS.SaveAs("Sample.pdf", memoryStream.ToArray());
}
}Step 8: Create a class file named FileUtil.cs and add the following code to invoke the JavaScript action to download the file in the browser.
public static class FileUtil
{
public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}Step 9: Add the following JavaScript function in the index.html file available under the wwwroot folder.
<script type = "text/javascript" >
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob)
{
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>Step 10: Build the project.
Click on Build → Build Solution or press Ctrl+Shift+B to build the project.
Step 11: Run the project.
Click the Start button (green arrow) or press F5 to run the app.
Prerequisites:
- Install .NET SDK: Ensure that you have the .NET SDK installed on your system. You can download it from the .NET Downloads page.
- Install Visual Studio Code: Download and install Visual Studio Code from the official website.
- Install C# Extension for VS Code: Open Visual Studio Code, go to the Extensions view (Ctrl+Shift+X), and search for ‘C#’. Install the official C# extension provided by Microsoft.
Step 1: Open the terminal (Ctrl+` ) and run the following command to create a new Blazor WebAssembly application.
dotnet new blazorwasm -n CreatePdfBlazorWASMApp
Step 2: Replace CreatePdfBlazorWASMApp with your desired project name.
Step 3: Navigate to the project directory using the following command
cd CreatePdfBlazorWASMApp
Step 4: Use the following command in the terminal to add the Syncfusion.Pdf.Net.Core package to your project.
dotnet add package Syncfusion.Pdf.Net.Core
Step 5: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in Program.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
var app = builder.Build();Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 6: Create a new cs file named ExportService.cs under the Data folder and include the following namespaces and class declaration in the file.
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
using Syncfusion.Drawing;Step 7: The PdfDocument object represents an entire PDF document that is being created. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data sources.
Add the following code sample in the ExportService class which illustrates how to create a simple PDF document using PdfTextElement and PdfGrid.
//Export weather data to PDF document.
public static MemoryStream CreatePdf(WeatherForecast[] forecasts)
{
if (forecasts == null)
{
throw new ArgumentNullException("Forecast cannot be null");
}
//Create a new PDF document.
using (PdfDocument pdfDocument = new PdfDocument())
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Add page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a service and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid.
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
using (MemoryStream stream = new MemoryStream())
{
//Saving the PDF document into the stream.
pdfDocument.Save(stream);
//Closing the PDF document.
pdfDocument.Close(true);
return stream;
}
}
}Step 8: Register the service in the Program.cs file as follows.
using CreatePdfBlazorWASMApp.Data;
// ...
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddSingleton<ExportService>();Step 9: Inject ExportService into FetchData.razor using the following code.
@inject ExportService ExportService
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.IOCreate a button in the FetchData.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Add the ExportToPdf method in the FetchData.razor page to call the export service.
@functions
{
protected async Task ExportToPdf()
{
using (MemoryStream pdfStream = ExportService.CreatePdf(forecasts))
{
await JS.SaveAs("Sample.pdf", pdfStream.ToArray());
}
}
}Step 10: Create a class file named FileUtil.cs and add the following code to invoke the JavaScript action to download the file in the browser.
public static class FileUtil
{
public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}Step 11: Add the following JavaScript function in the index.html file available under the wwwroot folder.
<script type = "text/javascript" >
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob)
{
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>Step 12: Build the project. Run the following command in terminal to build the project.
dotnet build
Step 13: Run the project.
Run the following command in the terminal to run the project.
dotnet run
Prerequisites:
- JetBrains Rider.
- Install .NET 8 SDK or later.
Step 1. Open JetBrains Rider and create a new Blazor WASM app project.
- Launch JetBrains Rider.
- Click new solution on the welcome screen.

- In the new Solution dialog, select Project Type as Web.
- Enter a project name and specify the location.
- Choose template as Blazor WebAssembly Standalone App.
- Select the target framework (e.g., .NET 8.0, .NET 9.0).
- Click create.

Step 2: Install the NuGet package from NuGet.org.
- Click the NuGet icon in the Rider toolbar and type Syncfusion.Pdf.Net.Core in the search bar.
- Ensure that “nuget.org” is selected as the package source.
- Select the latest Syncfusion.Pdf.Net.Core NuGet package from the list.
- Click the + (Add) button to add the package.

- Click the Install button to complete the installation.

Step 3: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in Program.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
var app = builder.Build();Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 4: Create a Razor file named FetchData.razor in the Pages folder if it does not already exist (the Blazor WebAssembly Standalone template provides a sample data page that you can reuse).
Step 5: Next, include the following namespaces in the FetchData.razor file.
@using Syncfusion.Pdf
@using Syncfusion.Pdf.Grid
@using Syncfusion.Drawing
@using Syncfusion.Pdf.Graphics
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.IOStep 6: Create a button in the FetchData.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Step 7: Define the @ExportToPdf click function on the FetchData.razor file.
The PdfDocument object represents an entire PDF document that is being created and add a PdfPage to it. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data sources.
@functions {
void ExportToPdf()
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
//Add Page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
//Create text element.
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a client side and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
//Create memory stream.
MemoryStream memoryStream = new MemoryStream();
//Save the PDF document.
pdfDocument.Save(memoryStream);
//Close the PDF document
pdfDocument.Close(true);
//Download the PDF document
JS.SaveAs("Sample.pdf", memoryStream.ToArray());
}
}Step 8: Create a class file named FileUtil.cs and add the following code to invoke the JavaScript action to download the file in the browser.
public static class FileUtil
{
public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}Step 9: Add the following JavaScript function in the index.html file available under the wwwroot folder.
<script type = "text/javascript" >
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob)
{
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>Step 10: Build the project.
Click the Build button in the toolbar or press Ctrl+Shift+B to build the project.
Step 11: Run the project.
Click the Run button (green arrow) in the toolbar or press Shift+F10 to run the app.
You can download a complete working sample from GitHub.
By executing the program, you will get the following output in the browser.

Click the Export to PDF button to get the PDF document with the following output.

Steps to create PDF documents in .NET MAUI Blazor application
Prerequisites:
- Install .NET SDK: Ensure that you have the .NET SDK installed on your system. You can download it from the .NET Downloads page.
- Install Visual Studio: Download and install Visual Studio from the official website.
Step 1: Create a new project by choosing .NET MAUI Blazor Hybrid and Web App template in Visual Studio.

Step 2: Install the Syncfusion.Pdf.NET NuGet package as a reference to your Blazor application from NuGet.org.

Step 3: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in MauiProgram.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
// Register the Syncfusion license
SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
builder.UseMauiApp<App>().ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
builder.Services.AddMauiBlazorWebView();
return builder.Build();
}
}Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 4: Next, include the following namespaces in the _Imports.razor file.
@using Syncfusion.Pdf
@using Syncfusion.Pdf.Graphics
@using Syncfusion.Pdf.Grid
@using Syncfusion.Drawing
@using BlazorMauiAppCreatePdfSample.ServicesStep 5: Create a button in the Weather.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Step 6: Define the @ExportToPdf click function on the Weather.razor file.
The PdfDocument object represents an entire PDF document that is being created and add a PdfPage to it. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data source.
@functions {
void ExportToPdf()
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
//Add Page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
//Create text element.
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a client side and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
using (MemoryStream ms = new MemoryStream())
{
// Save the PDF document to the memory stream
pdfDocument.Save(ms);
// Close the PDF document
pdfDocument.Close(true);
// Reset the memory stream position
ms.Position = 0;
// Create a SaveService instance
SaveService service = new SaveService();
// Save and view the PDF document
service.SaveAndView("Output.pdf", "application/pdf", ms);
}
}
}Step 7: Build the project.
Click on Build → Build Solution or press Ctrl+Shift+B to build the project.
Step 8: Run the project.
Click the Start button (green arrow) or press F5 to run the app.
Prerequisites:
- Install .NET SDK: Ensure that you have the .NET SDK installed on your system. You can download it from the .NET Downloads page.
- Install Visual Studio Code: Download and install Visual Studio Code from the official website.
- Install C# Extension for VS Code: Open Visual Studio Code, go to the Extensions view (Ctrl+Shift+X), and search for ‘C#’. Install the official C# extension provided by Microsoft.
Step 1: Open the terminal (Ctrl+` ) and run the following command to create a new .NET MAUI Blazor application.
dotnet new maui-blazor -n CreatePdfBlazorMaUIApp
Step 2: Replace CreatePdfBlazorMaUIApp with your desired project name.
Step 3: Navigate to the project directory using the following command
cd CreatePdfBlazorMaUIApp
Step 4: Use the following command in the terminal to add the Syncfusion.Pdf.NET package to your project.
dotnet add package Syncfusion.Pdf.Net
Step 5: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in MauiProgram.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
// Register the Syncfusion license
SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
builder.UseMauiApp<App>().ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
builder.Services.AddMauiBlazorWebView();
return builder.Build();
}
}Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 6: Next, include the following namespaces in the _Imports.razor file.
@using Syncfusion.Pdf
@using Syncfusion.Pdf.Graphics
@using Syncfusion.Pdf.Grid
@using Syncfusion.Drawing
@using BlazorMauiAppCreatePdfSample.ServicesStep 7: Create a button in the Weather.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Step 8: Define the @ExportToPdf click function on the Weather.razor file.
The PdfDocument object represents an entire PDF document that is being created and add a PdfPage to it. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data source.
@functions {
void ExportToPdf()
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
//Add Page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
//Create text element.
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a client side and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
using (MemoryStream ms = new MemoryStream())
{
// Save the PDF document to the memory stream
pdfDocument.Save(ms);
// Close the PDF document
pdfDocument.Close(true);
// Reset the memory stream position
ms.Position = 0;
// Create a SaveService instance
SaveService service = new SaveService();
// Save and view the PDF document
service.SaveAndView("Output.pdf", "application/pdf", ms);
}
}
}Step 9: Build the project.
Run the following command in the terminal to build the project.
dotnet build
Step 10: Run the project.
Run the following command in the terminal to run the project.
dotnet run
Prerequisites:
- JetBrains Rider.
- Install .NET 8 SDK or later.
Step 1. Open JetBrains Rider and create a new .NET MAUI Blazor Hybrid App project.
- Launch JetBrains Rider.
- Click New Solution on the welcome screen.

- In the New Solution dialog, select Project Type as MAUI (or Mobile / Cross-platform, depending on your Rider version).
- Enter a project name and specify the location.
- Choose template as .NET MAUI Blazor Hybrid App.
- Select the target framework (e.g., .NET 8.0, .NET 9.0).
- Click Create.

Step 2: Install the NuGet package from NuGet.org.
- Click the NuGet icon in the Rider toolbar and type Syncfusion.Pdf.NET in the search bar.
- Ensure that “nuget.org” is selected as the package source.
- Select the latest Syncfusion.Pdf.NET NuGet package from the list.
- Click the + (Add) button to add the package.

- Click the Install button to complete the installation.

Step 3: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in MauiProgram.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
// Register the Syncfusion license
SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
builder.UseMauiApp<App>().ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
builder.Services.AddMauiBlazorWebView();
return builder.Build();
}
}Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 4: Next, include the following namespaces in the _Imports.razor file.
@using Syncfusion.Pdf
@using Syncfusion.Pdf.Graphics
@using Syncfusion.Pdf.Grid
@using Syncfusion.Drawing
@using BlazorMauiAppCreatePdfSample.ServicesStep 5: Create a button in the Weather.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Step 6: Define the @ExportToPdf click function on the Weather.razor file.
The PdfDocument object represents an entire PDF document that is being created and add a PdfPage to it. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data source.
@functions {
void ExportToPdf()
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
//Add Page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
//Create text element.
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a client side and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
using (MemoryStream ms = new MemoryStream())
{
// Save the PDF document to the memory stream
pdfDocument.Save(ms);
// Close the PDF document
pdfDocument.Close(true);
// Reset the memory stream position
ms.Position = 0;
// Create a SaveService instance
SaveService service = new SaveService();
// Save and view the PDF document
service.SaveAndView("Output.pdf", "application/pdf", ms);
}
}
}Step 7: Build the project.
Click the Build button in the toolbar or press Ctrl+Shift+B to build the project.
Step 8: Run the project.
Click the Run button (green arrow) in the toolbar or press Shift+F10 to run the app.
You can download a complete working sample from GitHub.
By running the program, you will see the output in the browser when you click the Weather option in the left-side menu.

Click the Export to PDF button to download the PDF document with the following output.

Save the PDF document on different platforms
Create a folder named Services, then add a class called SaveService.cs within this folder, and insert the following code into it.
public partial class SaveService
{
//Method to save document as a file and view the saved document.
public partial void SaveAndView(string filename, string contentType, MemoryStream stream);
}Now, we need to implement platform-specific code to save the PDF document.
Android
Create a new class file named SaveAndroid.cs within the Android folder and add the following code to enable file saving on the Android platform.
public partial void SaveAndView(string filename, string contentType, MemoryStream stream)
{
string exception = string.Empty;
string? root = null;
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.App.Application.Context!.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads)!.AbsolutePath;
}
else
root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
Java.IO.File myDir = new(root + "/Syncfusion");
myDir.Mkdir();
Java.IO.File file = new(myDir, filename);
if (file.Exists())
{
file.Delete();
}
try
{
FileOutputStream outs = new(file);
outs.Write(stream.ToArray());
outs.Flush();
outs.Close();
}
catch (Exception e)
{
exception = e.ToString();
}
if (file.Exists())
{
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.N)
{
var fileUri = AndroidX.Core.Content.FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file);
var intent = new Intent(Intent.ActionView);
intent.SetData(fileUri);
intent.AddFlags(ActivityFlags.NewTask);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
Android.App.Application.Context.StartActivity(intent);
}
else
{
var fileUri = Android.Net.Uri.Parse(file.AbsolutePath);
var intent = new Intent(Intent.ActionView);
intent.SetDataAndType(fileUri, contentType);
intent = Intent.CreateChooser(intent, "Open File");
intent!.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
}NOTE
Android introduced a new runtime permission model for SDK version 23 and above. Include the following code to enable the Android file provider to save and view the generated PDF document.
- Create a new XML file with the name of
file_paths.xmlunder the Android project Resources/xml folder and add the following code in it.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>- Add the following code to the
AndroidManifest.xmlfile located under Properties/AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>iOS
Create a new class file named SaveIOS.cs within the iOS folder and include the following code to enable file saving on the iOS platform.
public partial void SaveAndView(string filename, string contentType, MemoryStream stream)
{
string exception = string.Empty;
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filePath = Path.Combine(path, filename);
try
{
FileStream fileStream = File.Open(filePath, FileMode.Create);
stream.Position = 0;
stream.CopyTo(fileStream);
fileStream.Flush();
fileStream.Close();
}
catch (Exception e)
{
exception = e.ToString();
}
if (contentType != "application/html" || exception == string.Empty)
{
UIViewController? currentController = UIApplication.SharedApplication!.KeyWindow!.RootViewController;
while (currentController!.PresentedViewController != null)
currentController = currentController.PresentedViewController;
QLPreviewController qlPreview = new();
QLPreviewItem item = new QLPreviewItemBundle(filename, filePath);
qlPreview.DataSource = new PreviewControllerDS(item);
currentController.PresentViewController((UIViewController)qlPreview, true, null);
}
}MacOS
Create a new class file named SaveMac.cs within the MacCatalyst folder and include the following code to enable file saving on the macOS platform.
public partial void SaveAndView(string filename, string contentType, MemoryStream stream)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filePath = Path.Combine(path, filename);
stream.Position = 0;
//Saves the document
using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.ReadWrite);
stream.CopyTo(fileStream);
fileStream.Flush();
fileStream.Dispose();
UIWindow? window = GetKeyWindow();
if (window != null && window.RootViewController != null)
{
UIViewController? uiViewController = window.RootViewController;
if (uiViewController != null)
{
QLPreviewController qlPreview = new();
QLPreviewItem item = new QLPreviewItemBundle(filename, filePath);
qlPreview.DataSource = new PreviewControllerDS(item);
uiViewController.PresentViewController((UIViewController)qlPreview, true, null);
}
}
}
public UIWindow? GetKeyWindow()
{
foreach (var scene in UIApplication.SharedApplication.ConnectedScenes)
{
if (scene is UIWindowScene windowScene)
{
foreach (var window in windowScene.Windows)
{
if (window.IsKeyWindow)
{
return window;
}
}
}
}
return null;
}Windows
Create a new class file named SaveWindows.cs within the Windows folder and include the following code to enable file saving on the Windows platform.
public async partial void SaveAndView(string filename, string contentType, MemoryStream stream)
{
StorageFile stFile;
string extension = Path.GetExtension(filename);
//Gets process windows handle to open the dialog in application process.
IntPtr windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
{
//Creates file save picker to save a file.
FileSavePicker savePicker = new();
if (extension == ".xlsx")
{
savePicker.DefaultFileExtension = ".xlsx";
savePicker.SuggestedFileName = filename;
//Saves the file as xlsx file.
savePicker.FileTypeChoices.Add("XLSX", new List<string>() { ".xlsx" });
}
if (extension == ".docx")
{
savePicker.DefaultFileExtension = ".docx";
savePicker.SuggestedFileName = filename;
//Saves the file as Docx file.
savePicker.FileTypeChoices.Add("DOCX", new List<string>() { ".docx" });
}
else if (extension == ".doc")
{
savePicker.DefaultFileExtension = ".doc";
savePicker.SuggestedFileName = filename;
//Saves the file as Doc file.
savePicker.FileTypeChoices.Add("DOC", new List<string>() { ".doc" });
}
else if (extension == ".rtf")
{
savePicker.DefaultFileExtension = ".rtf";
savePicker.SuggestedFileName = filename;
//Saves the file as Rtf file.
savePicker.FileTypeChoices.Add("RTF", new List<string>() { ".rtf" });
}
else if (extension == ".pdf")
{
savePicker.DefaultFileExtension = ".pdf";
savePicker.SuggestedFileName = filename;
//Saves the file as Pdf file.
savePicker.FileTypeChoices.Add("PDF", new List<string>() { ".pdf" });
}
else if (extension == ".pptx")
{
savePicker.DefaultFileExtension = ".pptx";
savePicker.SuggestedFileName = filename;
//Saves the file as pptx file.
savePicker.FileTypeChoices.Add("PPTX", new List<string>() { ".pptx" });
}
else if (extension == ".png")
{
savePicker.DefaultFileExtension = ".png";
savePicker.SuggestedFileName = filename;
//Saves the file as png file.
savePicker.FileTypeChoices.Add("PNG", new List<string>() { ".png" });
}
WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle);
stFile = await savePicker.PickSaveFileAsync();
}
else
{
StorageFolder local = ApplicationData.Current.LocalFolder;
stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
}
if (stFile != null)
{
using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite))
{
//Writes compressed data from memory to file.
using Stream outstream = zipStream.AsStreamForWrite();
outstream.SetLength(0);
//Saves the stream as file.
byte[] buffer = stream.ToArray();
outstream.Write(buffer, 0, buffer.Length);
outstream.Flush();
}
//Create message dialog box.
MessageDialog msgDialog = new("Do you want to view the document?", "File has been created successfully");
UICommand yesCmd = new("Yes");
msgDialog.Commands.Add(yesCmd);
UICommand noCmd = new("No");
msgDialog.Commands.Add(noCmd);
WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle);
//Showing a dialog box.
IUICommand cmd = await msgDialog.ShowAsync();
if (cmd.Label == yesCmd.Label)
{
//Launch the saved file.
await Windows.System.Launcher.LaunchFileAsync(stFile);
}
}
}The helper files mentioned above are available on this page.
Steps to create PDF documents in Blazor WebAssembly PWA
Prerequisites:
- Install .NET SDK: Ensure that you have the .NET SDK installed on your system. You can download it from the .NET Downloads page.
- Install Visual Studio: Download and install Visual Studio from the official website.
Step 1: Create a new Blazor WebAssembly Standalone App project.

Step 2: Enable PWA support by selecting the Progressive Web Application checkbox.

Step 3: Install the Syncfusion.Pdf.Net.Core NuGet package as a reference to your Blazor application from NuGet.org.

Step 4: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in Program.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
var app = builder.Build();Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 5: Create a Razor file named FetchData.razor in the Pages folder. Then, add the required namespace to the FetchData.razor file.
@using Syncfusion.Pdf
@using Syncfusion.Pdf.Grid
@using Syncfusion.Drawing
@using Syncfusion.Pdf.Graphics
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.IOStep 6: Create a button in the FetchData.razor using the following code.
<button class="btn btn-primary" @onclick="@CreatePDF">Create PDF document</button>Step 7: Implement the CreatePDF method in FetchData.razor.
Create a new async method named CreatePDF and include the following code example to create a PDF document in the Blazor WebAssembly Standalone app with PWA support.
@functions {
void CreatePDF()
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
// Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
// Add Page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
// Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
// Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
// Create text element.
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a client side and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
// Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
// Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
// Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
// Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
// Create memory stream.
MemoryStream memoryStream = new MemoryStream();
// Save the PDF document.
pdfDocument.Save(memoryStream);
// Closes the PDF document
pdfDocument.Close(true);
memoryStream.Position = 0;
// Download the PDF document
JS.SaveAs("Sample.pdf", memoryStream.ToArray());
}
}Step 8: Create a class file named FileUtil.cs and add the following code to invoke the JavaScript action to download the file in the browser.
public static class FileUtil
{
public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}Step 9: Add the following JavaScript function in the index.html file available under the wwwroot folder.
<script type = "text/javascript" >
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob)
{
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>Step 10: Build the project.
Click on Build → Build Solution or press Ctrl+Shift+B to build the project.
Step 11: Run the project.
Click the Start button (green arrow) or press F5 to run the application.
Prerequisites:
- Install .NET SDK: Ensure that you have the .NET SDK installed on your system. You can download it from the .NET Downloads page.
- Install Visual Studio Code: Download and install Visual Studio Code from the official website.
- Install C# Extension for VS Code: Open Visual Studio Code, go to the Extensions view (Ctrl+Shift+X), and search for ‘C#’. Install the official C# extension provided by Microsoft.
Step 1: Open the terminal (Ctrl+` ) and run the following command to create a new Blazor WebAssembly PWA application
dotnet new blazorwasm -o CreatePdfBlazorWASMApp --pwa
Step 2: Replace CreatePdfBlazorWASMApp with your desired project name.
Step 3: Navigate to the project directory using the following command
cd CreatePdfBlazorWASMApp
Step 4: Use the following command in the terminal to add the Syncfusion.Pdf.Net.Core package to your project.
dotnet add package Syncfusion.Pdf.Net.Core
Step 5: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in Program.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
var app = builder.Build();Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 6: Create a new cs file named ExportService.cs under the Data folder and include the following namespaces and class declaration in the file.
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
using Syncfusion.Drawing;Step 7: The PdfDocument object represents an entire PDF document that is being created. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data sources.
Add the following code sample in the ExportService class which illustrates how to create a simple PDF document using PdfTextElement and PdfGrid.
//Export weather data to PDF document.
public static MemoryStream CreatePdf(WeatherForecast[] forecasts)
{
if (forecasts == null)
{
throw new ArgumentNullException("Forecast cannot be null");
}
//Create a new PDF document.
using (PdfDocument pdfDocument = new PdfDocument())
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Add page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a service and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid.
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
using (MemoryStream stream = new MemoryStream())
{
//Saving the PDF document into the stream.
pdfDocument.Save(stream);
//Closing the PDF document.
pdfDocument.Close(true);
return stream;
}
}
}Step 8: Register the service in the Program.cs file as follows.
using CreatePdfBlazorWASMApp.Data;
// ...
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddSingleton<ExportService>();Step 9: Inject ExportService into FetchData.razor using the following code.
@inject ExportService ExportService
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.IOCreate a button in the FetchData.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Add the ExportToPdf method in the FetchData.razor page to call the export service.
@functions
{
protected async Task ExportToPdf()
{
using (MemoryStream pdfStream = ExportService.CreatePdf(forecasts))
{
await JS.SaveAs("Sample.pdf", pdfStream.ToArray());
}
}
}Step 10: Create a class file named FileUtil.cs and add the following code to invoke the JavaScript action to download the file in the browser.
public static class FileUtil
{
public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}Step 11: Add the following JavaScript function in the index.html file available under the wwwroot folder.
<script type = "text/javascript" >
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob)
{
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>Step 12: Build the project. Run the following command in the terminal to build the project.
dotnet build
Step 13: Run the project. Run the following command in the terminal to run the project.
dotnet run
Prerequisites:
- JetBrains Rider.
- Install .NET 8 SDK or later.
Step 1. Open JetBrains Rider and create a new Blazor WASM PWA app project.
- Launch JetBrains Rider.
- Click New Solution on the welcome screen.

- In the new Solution dialog, select Project Type as Web.
- Enter a project name and specify the location.
- Choose template as Blazor WebAssembly Standalone App.
- Select the target framework (e.g., .NET 8.0, .NET 9.0).
- Enable the Progressive Web Application (PWA) checkbox.
- Click create.

Step 2: Install the NuGet package from NuGet.org.
- Click the NuGet icon in the Rider toolbar and type Syncfusion.Pdf.Net.Core in the search bar.
- Ensure that “nuget.org” is selected as the package source.
- Select the latest Syncfusion.Pdf.Net.Core NuGet package from the list.
- Click the + (Add) button to add the package.

- Click the Install button to complete the installation.

Step 3: Register the Syncfusion license key. A trial watermark is added to every page of the generated PDF until a valid key is registered. Include the license key in Program.cs before initializing any Syncfusion component:
using Syncfusion.Licensing;
var builder = WebApplication.CreateBuilder(args);
// Register the Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR LICENSE KEY");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
var app = builder.Build();Replace "YOUR LICENSE KEY" with the license key associated with your Syncfusion® account. If you do not have a license key, you can request a free 30-day trial or apply for a Community License from the Syncfusion® website. For more information about registering a license key in your application, refer to the Syncfusion® Licensing Documentation.
Step 4: Create a Razor file named FetchData.razor in the Pages folder if it does not already exist (the Blazor WebAssembly Standalone template provides a sample data page that you can reuse).
Step 5: Next, include the following namespaces in the FetchData.razor file.
@using Syncfusion.Pdf
@using Syncfusion.Pdf.Grid
@using Syncfusion.Drawing
@using Syncfusion.Pdf.Graphics
@inject Microsoft.JSInterop.IJSRuntime JS
@using System.IOStep 6: Create a button in the FetchData.razor using the following code.
<button class="btn btn-primary" @onclick="@ExportToPdf">Export PDF</button>Step 7: Define the @ExportToPdf click function on the FetchData.razor file.
The PdfDocument object represents an entire PDF document that is being created and add a PdfPage to it. The PdfTextElement is used to add text in a PDF document and which provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. The PdfGrid allows you to create table by entering data manually or from an external data sources.
@functions {
void ExportToPdf()
{
int paragraphAfterSpacing = 8;
int cellMargin = 8;
//Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
//Add Page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();
//Create a new font.
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16);
//Create a text element to draw a text in PDF page.
PdfTextElement title = new PdfTextElement("Weather Forecast", font, PdfBrushes.Black);
PdfLayoutResult result = title.Draw(page, new PointF(0, 0));
PdfStandardFont contentFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
//Create text element.
PdfTextElement content = new PdfTextElement("This component demonstrates fetching data from a client side and Exporting the data to PDF document using Syncfusion .NET PDF library.", contentFont, PdfBrushes.Black);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
//Draw a text to the PDF document.
result = content.Draw(page, new RectangleF(0, result.Bounds.Bottom + paragraphAfterSpacing, page.GetClientSize().Width, page.GetClientSize().Height), format);
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
pdfGrid.Style.CellPadding.Left = cellMargin;
pdfGrid.Style.CellPadding.Right = cellMargin;
//Applying built-in style to the PDF grid
pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1);
//Assign data source.
pdfGrid.DataSource = forecasts;
pdfGrid.Style.Font = contentFont;
//Draw PDF grid into the PDF page.
pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(0, result.Bounds.Bottom + paragraphAfterSpacing));
//Create memory stream.
MemoryStream memoryStream = new MemoryStream();
//Save the PDF document.
pdfDocument.Save(memoryStream);
//Close the PDF document
pdfDocument.Close(true);
//Download the PDF document
JS.SaveAs("Sample.pdf", memoryStream.ToArray());
}
}Step 8: Create a class file named FileUtil.cs and add the following code to invoke the JavaScript action to download the file in the browser.
public static class FileUtil
{
public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}Step 9: Add the following JavaScript function in the index.html file available under the wwwroot folder.
<script type = "text/javascript" >
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob)
{
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>Step 10: Build the project.
Click the Build button in the toolbar or press Ctrl+Shift+B to build the project.
Step 11: Run the project.
Click the Run button (green arrow) in the toolbar or press Shift+F10 to run the app.
You can download a complete working sample from GitHub.
By executing the program, you will get the following output in the browser.

Click the Create PDF document button to download the generated PDF document with the following output.

Troubleshooting
| Issue | Possible Cause | Solution |
|---|---|---|
| License key not registered exception |
SyncfusionLicenseProvider.RegisterLicense not called |
Add license registration in Program.cs or MauiProgram.cs before app build |
QLPreviewItemBundle or PreviewControllerDS not found |
Helper classes not included | Copy the helper classes from the MAUI helper files page |
| Android file save fails on Android 11+ | Scoped storage restrictions | Ensure you are writing to the app-specific external storage directory (as shown in the code) and the FileProvider is configured correctly |
| Windows picker not visible | Window handle not initialized | Verify WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle) is called |
| iOS preview not displaying | Using deprecated KeyWindow API |
Use the ConnectedScenes API as shown in the updated iOS code sample |
Click here to explore the rich set of Syncfusion® PDF library features.
An online sample to get started with creating a PDF document is available here.