.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;
}
相关推荐
AAA大运重卡何师傅(专跑国道)8 小时前
【无标题】
开发语言·c#
xiaoshuaishuai817 小时前
C# AvaloniaUI ProgressBar用法
开发语言·c#
a11177617 小时前
粒子化系统(3D-Particles)THreeJS react
前端·html·jetson
半壶清水19 小时前
用python脚本加html自建的书法字典
开发语言·python·html
wearegogog12320 小时前
基于C#的电机监控上位机(串口通信+实时波形)
开发语言·c#
△曉風殘月〆20 小时前
C#如何Hook托管函数
c#·hook
雪豹阿伟21 小时前
18.C# —— 三层结构 + 接口架构实战(UI+Model+DAL+IDAL)
c#·上位机
雪豹阿伟21 小时前
17.C# —— 事件
c#·上位机
weixin_4280053021 小时前
C#调用 AI学习从0开始-第2阶段(Function Calling+工具调用智能体)-第9天实战
人工智能·学习·ai·c#·functioncalling
FuckPatience1 天前
C# 继承中的使用new的陷阱,和abstract /virtual 的不同
开发语言·c#