1

Roland Weigelt - How to Create a PNG File from a Web Page in C#

 2 years ago
source link: https://weblogs.asp.net/rweigelt/how-to-create-a-png-file-from-a-web-page-in-c?WT_mc_id=DOP-MVP-4025064
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Create a PNG File from a Web Page in C#

Wednesday, January 26, 2022

Both Google Chrome and Microsoft Edge provide a feature for creating a PNG file from the currently visible viewport. For this, you start the browser executable in “headless mode”, i.e., without the UI (command line argument --headless), and provide the path of the output file (—screenshot=<path>).

Using this from C# code is straightforward:

void HtmlToPng(string source, string outputFilePath)
{
    var arguments = $"--headless --disable-gpu --default-background-color=00000000 --window-size=1920,1080 --hide-scrollbars --screenshot=\"{outputFilePath}\" \"{source}\"";

    var process = new System.Diagnostics.Process();
    process.StartInfo.FileName = "msedge"; // or "chrome"
    process.StartInfo.Arguments = arguments;
    process.StartInfo.UseShellExecute = true;
    process.Start();
}

Examples:

HtmlToPng("https://www.example.com", @"C:\example\output.png");
HtmlToPng(@"C:\example\input.html", @"C:\example\output.png");

(For complete code, download the demo project on GitHub)

Details

  • By starting the process with UseShellExcute = true, we do not have to care about the exact location of the Edge (or Chrome) executable – specifying msedge or chrome is sufficient.
  • --disable-gpu is taken from the Google docs (we don’t need a GPU for what is basically one frame).
  • --default-background-color specifies the background color to use if the page itself has no background set. The color is a hex value in the format AARRGGBB (AA = alpha). 00000000 means transparent; 0 also works, but could be confused with “black” when reading the code later.
  • --window-size specifies the size of the area available for the webpage to render. The created PNG file will only show this area.
  • The --hide-scrollbars takes care of scrollbars that may appear if the page needs more space than available.

No Comments

Add a Comment

Name

As it will appear on the website

Email

Not displayed

Url

Your website

Comment

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK