This article explains how to integrate a Syncfusion SfSparkWinLoss Chart in a .NET MAUI Toolkit application and export it as a PDF. The chart is bound to data through a ViewModel, captured as an image stream, and embedded into a Syncfusion PDF document.
Let’s walk through the step-by-step process to achieve this behavior.
Step 1: Create the SparkWinLoss chart with the help of this guideline.
Step 2: Add the Syncfusion.Pdf.Net package to your project.
Step 3: Generate a PDF document for the SfSparkWinLoss chart
This step explains how to capture the rendered SfSparkWinLoss as an image and embed it into a PDF using Syncfusion’s PDF library in a .NET MAUI app. The approach works across platforms (Android, iOS, macOS, and Windows) and ensures the exported chart maintains clarity and layout fidelity.
private async void SparkWinLossButton_Clicked(object sender, EventArgs e)
{
if (sparkwinloss == null)
return;
PdfDocument document = new PdfDocument();
PdfPage page = document.Pages.Add();
PdfGraphics graphics = page.Graphics;
float width = (float)sparkwinloss.Width + 75;
float height = (float)sparkwinloss.Height + 125;
//To reduce the width and height of the Windows and MAC platform
#if !IOS && !ANDROID
width = (float)sparkwinloss.Width / 2.5f;
height = (float)sparkwinloss.Height / 1.5f;
#endif
PdfImage img = new PdfBitmap((await sparkwinloss.GetStreamAsync(ImageFileFormat.Png)));
//sparkwinloss.SaveAsImage();
graphics.DrawImage(img, new RectangleF(0, 0, width, height));
MemoryStream stream = new MemoryStream();
document.Save(stream);
document.Close(true);
stream.Position = 0;
SavePDF("SparkWinLossAsPDF.pdf", stream);
stream.Flush();
stream.Dispose();
}Step 4: Save the PDF document in the default Documents directory.
private async void SavePDF(string fileName, Stream stream)
{
fileName = Path.GetFileNameWithoutExtension(fileName) + ".pdf";
#if ANDROID
string path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).ToString();
#else
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
#endif
string filePath = Path.Combine(path, fileName);
using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.ReadWrite);
await stream.CopyToAsync(fileStream);
fileStream.Flush();
fileStream.Dispose();
}Note: To save the PDF document on Android and Windows Phone devices, you must enable file writing permissions on the device storage.
Output: