D2Sharp wraps the D2 diagramming library for .NET, allowing you to render D2 diagrams with C# in your .NET applications.
- Render diagrams as SVG
- Integrate with ASP.NET Core for web applications
- Includes a web demo for quick testing
- .NET 8.0 SDK or newer
- Go 1.22.2 or newer
- GCC (for compiling the Go wrapper)
You can check your setup using the provided scripts:
Windows:
.\depcheck.ps1
Unix-based systems:
./depcheck.sh
src/D2Sharp
: Main library projectexamples/D2Sharp.Web
: Web demo applicationsrc/D2Sharp/d2wrapper
: Go wrapper code
- Clone the repository
- Build the project:
dotnet build
Basic usage:
// Create an instance of D2Wrapper
// You can pass a logger instance if you want to enable logging
var wrapper = new D2Wrapper(logger);
// Define your D2 script as a string
var script = @"direction: right
A -> B -> C";
// Render the diagram
var svg = wrapper.RenderDiagram(script);
// The 'svg' variable now contains the SVG representation of your diagram
// You can save this to a file, display it in a web page, or process it further as needed
The RenderDiagram
method now returns a RenderResult
object, which includes both the rendered SVG (if successful) and detailed error information (if rendering failed). Here's how you can use it:
var wrapper = new D2Wrapper();
string script = @"
A -> B
B -> // This line has an error
C -> D
";
var result = wrapper.RenderDiagram(script);
if (result.IsSuccess)
{
Console.WriteLine("Diagram rendered successfully:");
Console.WriteLine(result.Svg);
}
else
{
Console.WriteLine("Error rendering diagram:");
Console.WriteLine($"Message: {result.Error.Message}");
if (result.Error.LineNumber.HasValue)
{
Console.WriteLine($"Line {result.Error.LineNumber}: {result.Error.LineContent}");
}
}
Running the web demo:
cd examples/D2Sharp.Web
dotnet run
This project would not be possible without the following open-source projects: