.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;
}
相关推荐
唐青枫9 小时前
C#.NET Channel 深入解析:高性能异步生产者消费者模型实战
c#·.net
anOnion18 小时前
构建无障碍组件之Switch Pattern
前端·html·交互设计
小峥降临1 天前
Rokid UXR 的手势追踪虚拟中更真实的手实战开发【含 工程源码 和 最终完成APK】
c#
晨星shine5 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530145 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526745 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526745 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang6 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
willow6 天前
html5基础整理
html
anOnion9 天前
构建无障碍组件之Radio group pattern
前端·html·交互设计