Skip to content
Bitavu

INTEGRATIONS · PDF AUTOMATION

Generate a PDF in C#

Design a reusable template in Bitavu Studio and fill it with data from your .NET app. Save a PDF to disk from a C# console app or return it as a download in ASP.NET Core.

.NET AND C#

Prepare a PDF template

You’ll need a Bitavu workspace with render credits and the .NET SDK. Both examples target .NET 10. Bitavu.Client 0.1.1 also supports .NET 11.

  1. Start with a layout in Studio

    In Bitavu Studio, choose Packing slip / delivery note for the .NET console example or Studio invoice for the ASP.NET Core example. For the packing slip, add the tracking QR code before saving the version you’ll render.

  2. Preview and save a version

    Test the layout with example data. Open Integrations → Prepare a template request, select the saved revision and open Use in your app. Copy the templateId and numeric revision. The request’s data shows the fields your app should send.

  3. Choose an API key for this template

    In Integrations → API keys, use a key with access to the template and Generate PDFs permission. If you need a new key, copy it when Studio shows it.

One packing slip template, two QR codes

Both PDFs use the same saved Bitavu template. Each order supplies the URL encoded in its QR code.

Scan each PDF to read its sample tracking URL.

In Test & preview, add a trackingUrl string to the existing order object in your Template example. Select Set fields from this JSON to include the new field in your template.

In the editor, replace the order barcode with a QR code from the Insert tab. In Properties → Encoded content, set the value to {{order.trackingUrl}}. Preview the PDF, save the version and copy its revision.

Select the QR code in the editor to see which field supplies its value.
Preview a second order with the same layout and a different tracking URL.

Generate and save PDFs in a .NET console app

Create a console project and install the Bitavu client.

dotnet new console -n BitavuPackingSlips -f net10.0
cd BitavuPackingSlips
dotnet add package Bitavu.Client --version 0.1.1

Supply the packing slip’s API key as the BITAVU_API_KEY environment variable. Replace Program.cs with the following code. The client serializes Order.TrackingUrl as order.trackingUrl in the JSON request.

using Bitavu;

if (args.Length != 2 || !long.TryParse(args[1], out var revision) || revision < 1)
    throw new ArgumentException("Pass the packing slip template ID and saved revision.");

var apiKey = Environment.GetEnvironmentVariable("BITAVU_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
    throw new InvalidOperationException("Set BITAVU_API_KEY before running the app.");

var client = new BitavuClient(apiKey);
foreach (var number in new[] { "PS-1042", "PS-1043" })
{
    var data = new
    {
        Organization = new { Name = "Example Dispatch", Address = "Demo warehouse" },
        Order = new
        {
            Number = number,
            Date = "14 November 2026",
            Reference = $"PO-{number[3..]}",
            Instructions = "Include the product care card.",
            PreparedBy = "Dispatch team",
            TrackingUrl = $"https://example.com/track/{number}",
        },
        Recipient = new { Name = "Demo Receiving", Address = "Example Road\nSample City" },
        Items = new[]
        {
            new { Sku = "BOT-750", Description = "Glass water bottle", Quantity = 4, Location = "A-03" },
            new { Sku = "CARD-01", Description = "Product care card", Quantity = 1, Location = "B-02" },
        },
    };

    var pdf = await client.RenderPdfAsync(args[0], revision, data, Guid.NewGuid().ToString("N"));
    await File.WriteAllBytesAsync($"packing-slip-{number.ToLowerInvariant()}.pdf", pdf.Bytes);
}

Substitute the template ID and saved revision from Studio. The program writes both PDFs to the current directory.

dotnet run -- YOUR_TEMPLATE_ID 1

ASP.NET CORE

Configure an ASP.NET Core app

dotnet new web -n BitavuInvoices -f net10.0
cd BitavuInvoices
dotnet add package Bitavu.Client --version 0.1.1
dotnet user-secrets init

Add the Bitavu section to appsettings.json, preserving the other settings. Replace the template ID and revision with the values from Studio.

{
  "Bitavu": {
    "TemplateId": "your-template-id",
    "TemplateRevision": 1
  }
}

Open your project’s .NET User Secrets file (in Visual Studio, choose Manage User Secrets on the project) and add the API key there. ASP.NET Core loads it when the app runs in Development.

{
  "Bitavu:ApiKey": "<your Bitavu API key>"
}

For a deployed app, use your hosting provider’s secret store to supply Bitavu__ApiKey to the server. Keep the key out of appsettings.json, source control, and browser code.

Inject the client into an invoice service

Replace Program.cs with the example below. ASP.NET Core reuses one BitavuClient and injects it into InvoiceRenderer. The client converts the C# properties to camel-case JSON, so Invoice.Number becomes invoice.number and UnitPrice becomes unitPrice.

using Bitavu;

var builder = WebApplication.CreateBuilder(args);

var apiKey = builder.Configuration["Bitavu:ApiKey"];
if (string.IsNullOrWhiteSpace(apiKey))
    throw new InvalidOperationException("Configure Bitavu:ApiKey.");

var templateId = builder.Configuration["Bitavu:TemplateId"];
var revision = builder.Configuration.GetValue<long>("Bitavu:TemplateRevision");
if (string.IsNullOrWhiteSpace(templateId) || revision < 1)
    throw new InvalidOperationException("Configure the template ID and saved revision.");

builder.Services.AddSingleton(new BitavuClient(apiKey));
builder.Services.AddSingleton(new InvoiceTemplate(templateId, revision));
builder.Services.AddTransient<InvoiceRenderer>();

var app = builder.Build();

app.MapPost("/invoices/sample/{operationId:guid}", async Task<IResult> (
    Guid operationId, InvoiceRenderer renderer, HttpContext context,
    ILogger<InvoiceRenderer> logger, CancellationToken cancellationToken) =>
{
    context.Response.Headers.CacheControl = "no-store";

    try
    {
        var pdf = await renderer.RenderSampleAsync(operationId, cancellationToken);
        return TypedResults.File(pdf.Bytes, "application/pdf", "invoice.pdf");
    }
    catch (BitavuApiException ex)
    {
        logger.LogWarning("Bitavu render failed: HTTP {Status}, {Code}, request {RequestId}",
            ex.StatusCode, ex.Code, ex.RequestId);
        return TypedResults.Problem("Bitavu could not render the invoice.", statusCode: 502);
    }
    catch (HttpRequestException)
    {
        logger.LogWarning("Could not reach Bitavu to render the invoice.");
        return TypedResults.Problem("Bitavu could not be reached.", statusCode: 502);
    }
});

app.Run();

sealed record InvoiceTemplate(string Id, long Revision);

sealed class InvoiceRenderer(BitavuClient client, InvoiceTemplate template)
{
    public Task<BitavuPdf> RenderSampleAsync(Guid operationId, CancellationToken cancellationToken)
    {
        var data = new
        {
            Invoice = new { Number = "INV-1001", Date = "2026-11-01", Due = "2026-11-15" },
            Client = new { Name = "Example Customer", Address = "100 Example Street" },
            Items = new[]
            {
                new { Description = "Design consultation", Quantity = 1, UnitPrice = 240m },
                new { Description = "Layout review", Quantity = 2, UnitPrice = 90m },
            },
            Notes = "Fictional invoice for testing the integration.",
        };

        return client.RenderPdfAsync(template.Id, template.Revision, data,
            operationId.ToString("N"), cancellationToken: cancellationToken);
    }
}

RenderPdfAsync pins the render to the revision you tested. To follow published updates that are compatible with that baseline, use RenderLatestPublishedPdfAsync and pass the tested revision as baseRevision. The result’s Revision tells you which saved version rendered.

Run the app and download the invoice

Start the app on your own computer. The http launch profile in the generated project sets the environment to Development.

dotnet run --launch-profile http -- --urls http://127.0.0.1:5080

From a second terminal, make a POST request. Replace the example UUID with one of your own. Use curl.exe on Windows if curl is a PowerShell alias.

curl --fail --output invoice.pdf -X POST http://127.0.0.1:5080/invoices/sample/37f27493-e462-479c-b5f1-495508ce629a

Open invoice.pdf to see invoice INV-1001, its customer details and two line items. If you retry the same render, use the same URL. For a different invoice or revision, use a new operation ID. The client sends the ID as the Idempotency-Key header.

In your application, load invoice data from your own records after checking that the signed-in user can access the invoice. Keep the key and the render call on the server.

Troubleshooting

  • The app asks for an API key

    For the console example, check that BITAVU_API_KEY is available to the process. For the web app, check that you initialized User Secrets in the web project and are running the Development profile.

  • The download fails

    Look in the server console for the Bitavu status and error code. For HTTP 401, check that the key is current. For HTTP 403, check the Generate PDFs permission and template access. If the template or revision can’t be found, copy both values again from Studio.

  • The PDF is missing values or the QR code

    Compare the request’s JSON with the template bindings in Studio. Check field names, nesting and the items array. For the QR code, check that order.trackingUrl is present in the request and bound in your saved version.

If you contact Bitavu Support, share the error code and request ID when available. Leave out the API key and invoice data.

Moving an existing report? Compare Crystal Reports and Bitavu for PDF generation.

← All support guides