nuget 引入 PuppeteerSharp
csharp
//调用
string htmlContent = "<h1>Hello, World!</h1>";
GenerateImageFromHtml(htmlContent, "output2.png").GetAwaiter();
csharp
/// <summary>
/// 保存为图片
/// </summary>
/// <param name="htmlContent"></param>
/// <param name="outputPath"></param>
/// <returns></returns>
static async Task GenerateImageFromHtml(string htmlContent, string outputPath)
{
// Launch headless Chrome browser
await new BrowserFetcher().DownloadAsync();
var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
// Create a new page
var page = await browser.NewPageAsync();
// Set the HTML content
await page.SetContentAsync(htmlContent);
// Generate screenshot of the page
await page.ScreenshotAsync(outputPath);
// Close the browser
await browser.CloseAsync();
Console.WriteLine($"Screenshot saved to: {outputPath}");
}
csharp
/// <summary>
/// 返回字节数组
/// </summary>
/// <param name="htmlContent"></param>
/// <returns></returns>
static async Task<byte[]> GenerateImageBytesFromHtml(string htmlContent)
{
// Launch headless Chrome browser
await new BrowserFetcher().DownloadAsync();
var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
// Create a new page
var page = await browser.NewPageAsync();
// Set the HTML content
await page.SetContentAsync(htmlContent);
// Generate screenshot of the page as bytes
var imageBytes = await page.ScreenshotDataAsync();
// Close the browser
await browser.CloseAsync();
return imageBytes;
}