Convert SVG files to PNG or JPEG using .NET

 
 
  • Gérald Barré

Recently, I had to convert an SVG file to PNG. I tried a few free online converters, but none of them were able to convert the image correctly. Indeed, they don't support custom fonts… Instead of wasting more time at searching for an existing tool, I opened Visual Studio and I made a quick application to convert my images!

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

Let's fix it! The idea is to use Chromium to render the SVG image at the desired size and then take a screenshot. The easiest way to automate Chromium in .NET is to use 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:

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 image!

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

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub