phronCare/Transversal/Services/PuppeteerPdfGeneratorService.cs
Leandro Hernan Rojas b6c63b874c
All checks were successful
CI/CD Pipeline / Build and Deploy with Docker Compose (push) Successful in 9m29s
Testing Razor PDF Generator
2025-05-15 19:24:12 -03:00

65 lines
2.5 KiB
C#

using System.Runtime.InteropServices;
using PuppeteerSharp.Media;
using PuppeteerSharp;
using Transversal.Interfaces;
using Transversal.Models;
namespace Transversal.Services
{
public class PuppeteerPdfGeneratorService : IPdfGeneratorService, IAsyncDisposable
{
private readonly Browser _browser;
public PuppeteerPdfGeneratorService()
{
string? executablePath = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
? "/usr/bin/chromium" // Docker/Linux
: null; // Windows local → que use Chrome instalado
_browser = Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true,
ExecutablePath = executablePath,
Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }
}).GetAwaiter().GetResult();
}
//public PuppeteerPdfGeneratorService()
//{
// // NO USAR BrowserFetcher NUNCA en entorno productivo Docker
// _browser = Puppeteer.LaunchAsync(new LaunchOptions
// {
// Headless = true,
// ExecutablePath = "/usr/bin/chromium", // ruta de chromium en la imagen docker
// Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }
// }).GetAwaiter().GetResult();
//}
public async Task<byte[]> GeneratePdfFromHtmlAsync(string htmlContent, PdfGenerationOptions options = null)
{
options ??= new PdfGenerationOptions();
using var page = await _browser.NewPageAsync();
await page.SetContentAsync(htmlContent);
var pdfOptions = new PdfOptions
{
Format = options.Format,
Landscape = options.Landscape,
PrintBackground = options.PrintBackground,
Scale = options.Scale,
MarginOptions = options.Margins ?? new MarginOptions(),
DisplayHeaderFooter = !string.IsNullOrEmpty(options.HeaderTemplate)
|| !string.IsNullOrEmpty(options.FooterTemplate),
HeaderTemplate = options.HeaderTemplate,
FooterTemplate = options.FooterTemplate
};
return await page.PdfDataAsync(pdfOptions);
}
public async ValueTask DisposeAsync()
{
if (_browser != null)
await _browser.CloseAsync();
}
}
}