Articles in this section

How to Export Html Shapes Into Image and Pdf Format in the Blazor Diagram (WebAssembly)

The Syncfusion Blazor Diagram component supports exporting diagrams in JPEG, PNG, SVG, and PDF formats. During export, the diagram is drawn on a canvas and then converted to the selected image format. However, drawing HTML elements using SVG on a canvas and converting the result to an image can cause security issues in the browser. For this reason, built-in support for exporting HTML nodes to images is not available in the diagram component.

HTML-to-image export can be achieved using the open-source html2canvas library in a Blazor WebAssembly application. With this library, you can export the diagram to both image and PDF formats via a JavaScript interop call.

For more information about the html2canvas library, see html2canvas: Screenshots with JavaScript (github.com)

The following steps explain how to export the HTML shapes into image format in a WASM application:

Step 1: Create a Blazor WebAssembly Application

Create a simple Blazor WebAssembly application. Follow the Create WASM application. guide if needed.

Step 2: Create a Diagram with HTML Template Shape Nodes

Create a diagram component with HTML template shape nodes. Refer to Create Diagram Nodes for instructions.

Step 3: Add the Export Code

Use the following C# and JavaScript code below to export the HTML shape to an image.

C#

       /// <summary>
       /// Asynchronously exports the diagram to an image using JavaScript interop.
       /// </summary>
       private async Task ExportImage()
       {
            await JS.InvokeAsync<object>("exportToImage", diagram.ID);
       } 

JavaScript

/**
* Asynchronously exports the content of an HTML element to an image.
* @param {string} elementId - The ID of the HTML element to export.
* @returns {Promise<void>}
*/
window.exportToImage = async function(elementId)
{
   var image = "";
   const diagramLayerElement = document.getElementById(elementId + '_diagramLayer_div');
   const htmlLayerElement= document.getElementById(elementId + '_htmlLayer');
   const clonedDiagramLayer= diagramLayerElement.cloneNode(true);
   const clonedHtmlLayer= htmlLayerElement.cloneNode(true);
   clonedDiagramLayer.appendChild(clonedHtmlLayer);
   const exportContainer = document.createElement('div');
   exportContainer.style.position = 'absolute';
   exportContainer.style.left = '-9999px';
   exportContainer.style.top = '-9999px';
   exportContainer.appendChild(clonedDiagramLayer);
   document.body.appendChild(exportContainer);
   await html2canvas(clonedDiagramLayer).then(canvas => image = canvas.toDataURL("image/png"));
   var link = document.createElement("a");
   link.href = image;
   link.download = "diagram.png";
   link.click();
} 

The following steps explain on how to export Html shapes into PDF format in a WASM application:

Step 1: Create a Blazor WebAssembly Application and Install the Required Package

Create a simple WebAssembly application. Follow the Create WASM application. guide if needed.

Install the following NuGet package to enable PDF export:

Screenshot_2024-05-15_154932.png

Step 2: Create a Diagram with HTML Template Shape Nodes

Create a diagram component with HTML template shape nodes. Refer to Create Diagram Nodes for instructions.

Step 3: Add the Export Code

Use the following C# and JavaScript code below to export the HTML shape to PDF.

C#:

   /// <summary>
   /// Asynchronously exports the diagram to a PDF file.
   /// </summary>
   private async Task ExportDiagram()
   {
       string image = await JS.InvokeAsync<string>("exportToPdf", diagram.ID);
       string[] images = new string[] { image };
       await ExportToPdf("diagram", PdfPageOrientation.Portrait, true, images);
   }

   /// <summary>
   /// Asynchronously exports the provided images to a PDF file.
   /// </summary>
   /// <param name="fileName">The name of the output PDF file.</param>
   /// <param name="orientation">The page orientation of the PDF.</param>
   /// <param name="allowDownload">Whether to trigger a browser download.</param>
   /// <param name="images">An array of base64-encoded image strings.</param>
   /// <returns>The base64-encoded PDF string if allowDownload is false; otherwise, an empty string.</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 };
       DiagramRect bounds = await JS.InvokeAsync<DiagramRect>("getDiagramBounds", diagram.ID);
       document.PageSettings.Height = (float)bounds.Height;
       document.PageSettings.Width = (float)bounds.Width;
       string base64String;
       var diagramImages = images;
       for (int i = 0; i < diagramImages.Count(); i++)
       {
           base64String = diagramImages[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;
               PdfBitmap image = new PdfBitmap(stream);
               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

window.getDiagramBounds = function getDiagramBounds(id) {
   var diagram = document.getElementById(id + "_diagramLayer_div");
   var bounds = diagram.getBoundingClientRect();
   return bounds;
}

/**
* Asynchronously exports the content of an HTML element to a base64-encoded image string.
* @param {string} elementId - The ID of the HTML element to export.
* @returns {Promise<string>} - A Promise that resolves with the base64-encoded image string.
*/
window.exportToPdf = async function (elementId) {
   const diagramLayerElement = document.getElementById(elementId + '_diagramLayer_div');
   const htmlLayerElement= document.getElementById(elementId + '_htmlLayer');
   const clonedDiagramLayer= diagramLayerElement.cloneNode(true);
   const clonedHtmlLayer= htmlLayerElement.cloneNode(true);
   clonedDiagramLayer.appendChild(clonedHtmlLayer);
   const exportContainer= document.createElement('div');
   exportContainer.style.position = 'absolute';
   exportContainer.style.left = '-9999px';
   exportContainer.style.top = '-9999px';
   exportContainer.appendChild(clonedDiagramLayer);
   document.body.appendChild(exportContainer);
   var image = "";
   await html2canvas(clonedDiagramLayer).then(canvas => image = canvas.toDataURL("image/png"));
   document.body.removeChild(exportContainer);
   return image;
} 

Note: The html2canvas library exports the diagram as a single page only. Multi-page export is not supported.

You can download the complete working sample from here.

The following screenshot illustrates the output of the sample:

Screenshot_2024-05-15_155717.png

Conclusion:

We hope you enjoyed learning how to export HTML shapes into image and PDF format in Blazor Diagram.

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, support portal, 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)
Access denied
Access denied