Articles in this section
Category / Section

How to export the Blazor Diagram to PDF?

6 mins read

In a Blazor Diagram, there is no built-in support to convert the diagram to a PDF file directly. However, this can be achieved by exporting the diagram as a base64-encoded image and then converting the image to a PDF using Syncfusion.PdfExport.PdfDocument. You can invoke JavaScript functions to download the PDF file automatically.

Code Snippet:

The following code demonstrates how to export a Blazor Diagram to a PDF file:

@using Syncfusion.PdfExport;

@using Syncfusion.Blazor.Diagram
@using Syncfusion.Blazor.Buttons
@inject IJSRuntime JS;

<SfButton Content="ExportPDF" OnClick="@ExportPDF" />
<SfDiagramComponent Height="600px" @ref="@diagram">
</SfDiagramComponent>

@code{
   // Reference the diagram
   SfDiagramComponent diagram;

   /// <summary>
   /// Handles the ExportPDF button click event.
   /// Exports the diagram as a base64 image and converts it to a PDF.
   /// </summary>
   private async void ExportPDF()
   {
       DiagramExportSettings print = new DiagramExportSettings();
       print.Region = DiagramPrintExportRegion.PageSettings;
       print.PageWidth = 500;
       print.PageHeight = 800;
       print.Orientation = PageOrientation.Portrait;
       print.FitToPage = true;
       print.Margin = new DiagramThickness() { Left = 30, Top = 20, Right = 10, Bottom = 10 };
       print.ClipBounds = new DiagramRect() { X = 200, Y = 200, Width = 200, Height = 200 };
       // Export the diagram to base64
       var images = await diagram.ExportAsync(DiagramExportFormat.PNG, print);
       var pdforientation = PageOrientation.Portrait == PageOrientation.Landscape ? PdfPageOrientation.Landscape : PdfPageOrientation.Portrait;
       await ExportToPdf("diagram", pdforientation, true, images);        
   }
   /// <summary>
   /// Exports the base64 image of the diagram to a PDF file.
   /// </summary>
   /// <param name="fileName">Name of the PDF file to be saved.</param>
   /// <param name="orientation">Orientation of the PDF pages.</param>
   /// <param name="allowDownload">Indicates whether to allow automatic download of the PDF.</param>
   /// <param name="images">Array of base64 encoded images of the diagram.</param>
   /// <returns>A task representing the asynchronous operation.</returns>
   private async Task<string> ExportToPdf(string fileName, PdfPageOrientation orientation, bool allowDownload, string[] images)
   {
       PdfDocument document = new PdfDocument();
       document.PageSettings.Orientation = orientation;
       document.PageSettings.Margins = new PdfMargins() { Left = 0, Right = 0, Top = 0, Bottom = 0 };
       string base64String;
       var dict = images;
       for (int i = 0; i < dict.Count(); i++)
       {
           base64String = dict[i];
           using (MemoryStream initialStream = new MemoryStream(Convert.FromBase64String(base64String.Split("base64,")[1])))
           {
               Stream stream = initialStream as Stream;
               PdfPage page = document.Pages.Add();
               PdfGraphics graphics = page.Graphics;
               #pragma warning disable CA2000
               PdfBitmap image = new PdfBitmap(stream);
               #pragma warning restore CA2000
               graphics.DrawImage(image, 0, 0);
           }
       }
       using (MemoryStream memoryStream = new MemoryStream())
       {
           document.Save(memoryStream);
           memoryStream.Position = 0;
           base64String = Convert.ToBase64String(memoryStream.ToArray());
           if (allowDownload)
           {
               await JSRuntimeExtensions.InvokeAsync<string>(JS, "downloadPdf", new object[] { base64String, fileName });
               base64String = string.Empty;
           }
           else
           {
               base64String = "data:application/pdf;base64," + base64String;
           }
           document.Dispose();
       }
       return base64String;
   }

 } 

JavaScript Code

Add the following JavaScript functions to your project to handle the PDF download:

/**
* Downloads the PDF file.
* @param {string} base64String - The base64 encoded PDF string.
* @param {string} fileName - The name of the PDF file to be downloaded.
*/
function downloadPdf(base64String, fileName) {
   var sliceSize = 512;
   var byteCharacters = atob(base64String);
   var byteArrays = [];

   for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
       var slice = byteCharacters.slice(offset, offset + sliceSize);
       var byteNumbers = new Array(slice.length);

       for (var i = 0; i < slice.length; i++) {
           byteNumbers[i] = slice.charCodeAt(i);
       }

       var byteArray = new Uint8Array(byteNumbers);
       byteArrays.push(byteArray);
   }

   var blob = new Blob(byteArrays, { type: 'application/pdf' });
   var blobUrl = window.URL.createObjectURL(blob);
   triggerDownload("PDF", fileName, blobUrl);
}

/**
* Triggers the download of the file.
* @param {string} type - The type of the file.
* @param {string} fileName - The name of the file.
* @param {string} url - The URL of the file.
*/
function triggerDownload(type, fileName, url) {
   var anchorElement = document.createElement('a');
   anchorElement.download = fileName + '.' + type.toLowerCase();
   anchorElement.href = url;
   anchorElement.click();
}

You can download the complete working sample from here.

Note: If you want to export a diagram with HTML and Native shapes, please refer to this KB article link.

Conclusion:

We hope you enjoyed learning about how to export the Blazor Diagram to PDF.

You can refer to our Blazor Diagram feature tour page to learn about its other groundbreaking features, documentation, and how to quickly get started with configuration specifications. You can also explore our Blazor Diagram example to understand how to create and manipulate data.

For current customers, our Blazor components are available on the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to evaluate our Blazor Diagram and other Blazor components.

If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied