Category / Section
How to export the charts to PDF in Xamarin.Android
2 mins read
You can export a chart to a PDF by converting the chart into stream. From the chart stream, you can get the PDF of the chart using Syncfusion.Pdf.PdfDocument. The following code snippet demonstrates how to export a chart to a PDF.
C#
void ExportToPdfButton_Click(object sender, EventArgs e) { ExportChart ("SfChart", sfChart); } public void ExportChart(string filename, object obj) { var nativechart = obj as Com.Syncfusion.Charts.SfChart; nativechart.DrawingCacheEnabled = true; nativechart.SaveEnabled = true; using (Bitmap bitmap = nativechart.DrawingCache) { Java.IO.File imagePath = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/Pictures/" + filename); imagePath.CreateNewFile(); using (Stream fileStream = new FileStream(imagePath.AbsolutePath, FileMode.OpenOrCreate)) { try { bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, fileStream); //Create a new PDF document. Syncfusion.Pdf.PdfDocument document = new Syncfusion.Pdf.PdfDocument(); PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics; graphics.DrawImage(PdfImage.FromStream(fileStream), 0, 20, page.GetClientSize().Width, page.GetClientSize().Height-15); MemoryStream stream = new MemoryStream(); document.Save(stream); document.Close(true); SavePDF("Chart.pdf", "application/pdf", stream); } finally { fileStream.Flush(); fileStream.Close(); nativechart.DrawingCacheEnabled = false; } } } } void SavePDF(string fileName, String contentType, MemoryStream stream) { string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) file.Delete(); try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { } if (file.Exists()) { Android.Net.Uri path = Android.Net.Uri.FromFile(file); string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType(path, mimeType); this.StartActivity(Intent.CreateChooser(intent, "Choose App")); } }
Sample output
Exported PDF