.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;
}
相关推荐
rockey6271 小时前
AScript之字符串模板
c#·.net·script·expression·动态脚本
will_net2 小时前
Redis集群部署+Redis 链接地址放入Aollo +c#项目接入Redis
redis·c#·bootstrap
轻松西西莱尔3 小时前
谷歌+斯坦福+CMU 等五家 203 页综述,我做了个HTML把主动式AI的边界跑给你看
前端·html·agent
BuHuaX9 小时前
Lua 与 ToLua:运行机制及热更新原理
开发语言·unity·junit·c#·lua
asdzx679 小时前
C# 操作 PDF 元数据:从属性写入到字段提取的完整流程
前端·pdf·c#
MaAidan11 小时前
用 Agent 排查线上问题:SLS 日志分析 + DB/Redis 数据验证,一条链路搞清楚
前端·bootstrap·html
氷凌公子11 小时前
算法与UI拆分中遇到的问题及解决方式
c#·onnx·yolov26
1-1=012 小时前
C# 泛型
c#·.net·.netcore
砚凝霜12 小时前
保姆级 | CTF Lemon:禁用右键/F12 怎么破?查看源码 + HTML 注释拿 flag
前端·html