Convert SVG files to PNG or JPEG using .NET

 
 
  • Gérald Barré

I recently needed to convert an SVG file to PNG. I tried several free online converters, but none of them produced a correct result. They lack support for custom fonts and other features that only browsers handle properly.

Rather than spending more time searching for an existing tool, I built a small application to handle the conversion myself.

Example of a buggy SVG to PNG conversion (original SVG)

The solution is to use Chromium to render the SVG at the desired size and then capture a screenshot. The easiest way to automate Chromium in .NET is with Playwright.

#Implementation

Create an empty console application:

Shell
dotnet new console

Add the PlaywrightSharp package:

Shell
dotnet add package PlaywrightSharp

Replace the content of Program.cs with the following content:

Program.cs (C#)
var svgPath = @"icon.svg";
var outputPath = @"icon.png"; // Support png or jpg
var width = 512;
var height = 512;

await PlaywrightSharp.Playwright.InstallAsync();
using var playwright = await PlaywrightSharp.Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();

await page.SetViewportSizeAsync(width, height);
await page.GoToAsync(System.IO.Path.GetFullPath(svgPath));

var item = await page.QuerySelectorAsync("svg");
await item.ScreenshotAsync(outputPath, omitBackground: true); // omitBackground allows to keep transparency

Finally, you can run the application:

Shell
dotnet run

It should generate the PNG file!

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?