.net core 将html 转为图片

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;
}
相关推荐
凯丨5 小时前
AI 蠕虫来了:恶意文档如何通过 Copilot for Word 自我传播?
人工智能·c#·copilot
Aaron - Wistron6 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
骊城英雄7 小时前
基于C#+avalonia ui实现的跨平台点胶机灌胶监控控制上位机软件
开发语言·ui·c#
吾儿良辰7 小时前
一个被BCL遗忘的高性能集合:C# CircularBuffer<T>深度解析
开发语言·windows·c#
哎呦喂我去去去7 小时前
C#实现屏幕墙:同时监控多个电脑桌面(支持Windows、信创Linux、银河麒麟、统信UOS)
linux·windows·c#
caishenzhibiao9 小时前
期货先行者主图 同花顺期货通指标
java·c语言·c#
库拉库拉里9 小时前
Word文档的标题总是自动出现首行缩进怎么办?
c#·word·xhtml
在世修行9 小时前
从零打造 C# 工业视觉检测系统(一):项目全景与架构设计
c#·视觉检测
牡丹雅忻111 小时前
AES 加密模式演进:从 ECB、CBC 到 GCM 的 C# 深度实践
java·开发语言·c#
脚踏实地皮皮晨11 小时前
002002002_DepandencyObject类2
开发语言·windows·算法·c#·visual studio