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)
Create an empty console application:
dotnet new console
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:
It should generate the png image!
Do you have a question or a suggestion about this post? Contact me!