BoletoNetCore

repository·master·Indexed 42 days ago

https://github.com/boletonet/boletonetcore

A .NET Core implementation of the Boleto2Net library for managing Brazilian bank slips (boletos). It provides capabilities for generating, reading, and processing CNAB remittance and return files, as well as rendering boletos to PDF, PNG, and JPEG formats using a Playwright-based Chromium renderer.

Tokens
5.2K
Snippets
16
Records
26
Agent score
52%

What's inside BoletoNetCore

  1. Overview of BoletoNetCore

    master

    BoletoNetCore is a .NET Core adaptation of the original Boleto2Net project. It is designed to handle the logic for reading remittance (remessa) and return (retorno) files, as well as the rules for generating bank slips (boletos) in hypertext.

    Key characteristics:

    • Multi-target support: The core logic is compatible with both netstandard2.0 and net40.
    • Modular Architecture: The project is split into a main logic core (BoletoNetCore), a PDF generation service (BoletoNetCore.Pdf), and a testing suite (BoletoNetCore.Testes).
  2. How BoletoNetCore.Playwright works

    master

    The library uses Microsoft Playwright to control a headless Chromium instance to ensure high visual fidelity with the original HTML.

    The rendering lifecycle:

    1. The boleto HTML is generated via BoletoBancario.MontaHtmlEmbedded().
    2. The HTML content is loaded into a browser page.
    3. Playwright captures the page:
      • PDF: via print emulation.
      • Images: via screenshots.
    4. The browser instance is managed as a thread-safe singleton and remains active for subsequent requests to optimize performance.

    Key Architectural Components:

    • IHtmlRenderer: The primary interface for multi-format rendering.
    • PlaywrightHtmlRenderer: The implementation managing the browser lifecycle.
    • OutputFormat: A discriminated union containing PdfFormat, PngFormat, and JpegFormat.
    • BrowserManager: Handles Chromium lifecycle, including automatic crash recovery and concurrency control via SemaphoreSlim.
  3. How the Playwright Renderer behaves

    master

    Singleton Thread-Safe

    The renderer is registered as a singleton to reuse the browser process across all requests. A single Chromium instance handles concurrent requests up to the MaxConcurrency limit.

    Prewarm

    If PrewarmOnStart = true, an IHostedService is registered to initialize the browser during application startup. This eliminates the ~500ms delay on the first rendering. Note: This requires an ASP.NET Core or Generic Host.

    Crash Recovery

    With RestartOnFailure = true, the browser restarts automatically if the Chromium process fails. Ongoing requests will receive an error, but subsequent requests will function normally.

  4. Use ArquivoRemessa in BoletoNetCore

    master

    In BoletoNetCore, the ArquivoRemessa class has been restructured. Instead of passing all bank and remittance details into the GerarArquivoRemessa method, you now pass the bank information during instantiation. The GerarArquivoRemessa method is simplified to accept only the list of boletos and the target stream.

    // BoletoNetCore implementation
    var rem = new ArquivoRemessa(_banco, TipoArquivo.CNAB240, 1); //<== IMPLEMENTAR AQUI NUMERO SEQUENCIAL DO ARQ REMESSA!!!
    MemoryStream ms = new MemoryStream();
    rem.GerarArquivoRemessa(boletos, ms);
    retBoletos.ArquivoRemessa = Encoding.Default.GetString(ms.ToArray());
  5. Install Playwright Chromium browser

    master

    Before running the BoletoNetCore.Playwright.ConsoleApp, you must install the Chromium browser via the Playwright script.

    For a standard build:

    dotnet build -o ./build
    pwsh ./build/playwright.ps1 install chromium

    For a Release build:

    dotnet build -c Release -o ./build
    pwsh ./build/playwright.ps1 install chromium
    dotnet build -o ./build
    pwsh ./build/playwright.ps1 install chromium
  6. Configure BoletoNetCore.Playwright with Dependency Injection

    master

    For ASP.NET Core or applications using Microsoft.Extensions.DependencyInjection, use the BoletoNetCore.Playwright.Extensions package to register the renderer.

    1. Install the extension package:

      dotnet add package BoletoNetCore.Playwright.Extensions
    2. Register in your service container:

    // Program.cs
    services.AddPlaywrightRenderer(options =>
    {
        options.MaxConcurrency = 4;
        options.PrewarmOnStart = true;
    });

    Configuration options include MaxConcurrency and PrewarmOnStart. For full details on appsettings.json configuration, crash recovery, and prewarming, refer to the BoletoNetCore.Playwright.Extensions documentation.

    services.AddPlaywrightRenderer(options =>
    {
        options.MaxConcurrency = 4;
        options.PrewarmOnStart = true;
    });
  7. Install BoletoNetCore.Pdf for Linux environments

    master

    If you are using the BoletoNetCore.Pdf package to generate PDFs on Linux (specifically Debian-based environments), you must install the following system dependencies via apt-get:

    apt-get install -y libfontconfig1 libxrender1 libxext6

    Additionally, you must ensure that the wkhtmltopdf binary has execution permissions. Locate the binary within your project's output directory and run chmod +x on it:

    chmod +x "<Path_to_project>/BoletoNetCore.Testes/bin/Debug/net7.0/Rotativa/Linux/wkhtmltopdf"
    apt-get install -y libfontconfig1 libxrender1 libxext6
    
    chmod +x "<Caminho do projeto>/BoletoNetCore.Testes/bin/Debug/net7.0/Rotativa/Linux/wkhtmltopdf"
  8. Install BoletoNetCore.Playwright

    master

    To use the Playwright renderer for Brazilian bank slips (boletos), you need to install the NuGet package and the required Chromium browser instance.

    1. Install the NuGet package:

      dotnet add package BoletoNetCore.Playwright
    2. Install Chromium: The library requires a Chromium browser. You can generate and run the installation script provided by the project:

      # Build the project to generate the installation script
      dotnet build -o ./build
      
      # Run the PowerShell script to install Chromium
      pwsh ./build/playwright.ps1 install chromium
    dotnet add package BoletoNetCore.Playwright
    dotnet build -o ./build
    pwsh ./build/playwright.ps1 install chromium
  9. Migrate from Boleto.Net to BoletoNetCore

    master

    To migrate an existing project from the legacy Boleto.Net to BoletoNetCore, follow these steps:

    1. Update Solution: Add the BoletoNetCore project to your solution and remove the old version. Perform a 'clean' on the solution to identify reference errors, then replace old references with Boleto2Net.
    2. Refactor Code: Most changes are due to code restructuring. Pay close attention to the ArquivoRemessa class and PDF generation methods, as their signatures have changed.
    3. Install PDF Dependency: If you need PDF generation capabilities, you must explicitly add the BoletoNetCore.Pdf NuGet package to your project.
  10. Migrate from Boleto2Net to BoletoNetCore

    master

    If you are migrating an existing application from Boleto2Net to BoletoNetCore, be aware of the following breaking changes:

    1. Terminology Changes:
      • Cedente is now Beneficiario.
      • Sacado is now Pagador.
    2. CNAB Return Files: CodOcorrencia has been replaced by CodMovimentoRetorno.
    3. PDF Generation:
      • You must install the BoletoNetCore.Pdf NuGet package.
      • Use BoletoNetCorePdfProxy instead of BoletoNetCoreProxy.
    4. WebForms: This project does not use System.Web, so WebForms-specific components for the Visual Studio Editor are not available.
  11. Render boletos to PDF, PNG, or JPEG

    master

    You can render a single boleto or a collection of boletos directly using the RenderPlaywright extension method. The library supports multiple output formats.

    Direct Usage

    // Render to PDF (Default settings)
    byte[] pdf = boleto.RenderPlaywright(PdfFormat.Default);
    
    // Render to PNG (Default settings)
    byte[] png = boleto.RenderPlaywright(PngFormat.Default);
    
    // Render to JPEG with custom quality
    byte[] jpeg = boleto.RenderPlaywright(new JpegFormat(Quality: 90));
    
    // Render multiple boletos into a single PDF batch
    byte[] pdfLote = boletos.RenderPlaywright(PdfFormat.Default);
    byte[] pdf = boleto.RenderPlaywright(PdfFormat.Default);
    byte[] png = boleto.RenderPlaywright(PngFormat.Default);
    byte[] jpeg = boleto.RenderPlaywright(new JpegFormat(Quality: 90));
    byte[] pdfLote = boletos.RenderPlaywright(PdfFormat.Default);