.net core 将html 转为图片

nuget 引入 PuppeteerSharp

//调用
string htmlContent = "<h1>Hello, World!</h1>";
GenerateImageFromHtml(htmlContent, "output2.png").GetAwaiter();
   /// <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}");
}

  

    /// <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;
}

相关推荐

  1. .net core html 转为图片

    2024-03-27 09:00:03       33 阅读
  2. PHPHTML标签转化图片

    2024-03-27 09:00:03       41 阅读
  3. html转换图片

    2024-03-27 09:00:03       53 阅读
  4. html字符串中的base64图片转换成file并上传

    2024-03-27 09:00:03       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-27 09:00:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-27 09:00:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-27 09:00:03       87 阅读
  4. Python语言-面向对象

    2024-03-27 09:00:03       96 阅读

热门阅读

  1. 使用 PointNet 和 PyTorch3D 进行点云分类

    2024-03-27 09:00:03       34 阅读
  2. QEMU安装和使用@Ubuntu(待续)

    2024-03-27 09:00:03       43 阅读
  3. Vue2进阶——组件通信

    2024-03-27 09:00:03       39 阅读
  4. Redis 服务

    2024-03-27 09:00:03       28 阅读