Convert SVG files to PNG or JPEG using .NET
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 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:
dotnet new console
Add the PlaywrightSharp
package:
dotnet add package PlaywrightSharp
Replace the content of Program.cs
with the following content:
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:
dotnet run
It should generate the PNG image!
Do you have a question or a suggestion about this post? Contact me!