InvoiceGenerator.Core 2.0.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package InvoiceGenerator.Core --version 2.0.2
                    
NuGet\Install-Package InvoiceGenerator.Core -Version 2.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="InvoiceGenerator.Core" Version="2.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="InvoiceGenerator.Core" Version="2.0.2" />
                    
Directory.Packages.props
<PackageReference Include="InvoiceGenerator.Core" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add InvoiceGenerator.Core --version 2.0.2
                    
#r "nuget: InvoiceGenerator.Core, 2.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package InvoiceGenerator.Core@2.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=InvoiceGenerator.Core&version=2.0.2
                    
Install as a Cake Addin
#tool nuget:?package=InvoiceGenerator.Core&version=2.0.2
                    
Install as a Cake Tool

Invoice Generator Library

NuGet version NuGet downloads

Version 2.0.1

A .NET 8 library for generating Invoice PDF reports from Razor templates using IronPdf. This library is designed to be easy to use, providing a simple API for generating complex PDF documents with text, tables, and more.

Features

  • Generate PDF documents from Razor templates (.cshtml)
  • Uses IronPdf for HTML-to-PDF conversion
  • Dependency injection support for easy integration with ASP.NET Core applications
  • Model-based report generation (strongly typed views)
  • Support for custom fields in invoices via a flexible dictionary, allowing for easy addition of custom data to invoices
  • Cross-platform support (Windows, macOS, Linux)
  • Simple, consolidated API with a single entry point for configuration
  • Customizable PDF options including page size, orientation, and margins

Getting Started

Prerequisites

  • .NET 8.0 SDK or later

Installation

Clone the repository and build the solution:

git clone <your-repository-url> # Replace with your repo URL
cd <repository-folder>
dotnet build

Alternatively, you can install the library via NuGet:

Install-Package InvoiceGenerator.Core

Usage

The primary way to use this library is by leveraging dependency injection.

Complete Example

Here's a complete example of how to use the library to generate an invoice PDF:

using Microsoft.Extensions.DependencyInjection;
using InvoiceGenerator.Core.Contracts;
using InvoiceGenerator.Core.Extensions;
using InvoiceGenerator.Core.Services;
using System.IO;
using System;

// 1️⃣ Setup DI for your PDF services
var services = new ServiceCollection()
                .AddInvoiceGenerator() // registers all required services
                .BuildServiceProvider();

// Get the invoice generator service
var invoiceGenerator = services.GetRequiredService<IInvoiceGenerator>();

// 2️⃣ Create your invoice model
var invoice = new Invoice
{
    Number = "INV-001",
    IssuedDate = DateTime.Today,
    DueDate = DateTime.Today.AddDays(30),
    SellerAddress = new Address
    {
        CompanyName = "ACME Corp",
        Street = "123 Main St",
        City = "Metropolis",
        State = "NY",
        Email = "sales@acme.com",
    },
    CustomerAddress = new Address
    {
        CompanyName = "Wayne Enterprises",
        Street = "456 Oak Ave",
        City = "Gotham",
        State = "NJ",
        Email = "wayne@example.com",
    },
    LineItems =
    [
        new() { Name = "Product A", Price = 10.00m, Quantity = 2 },
        new() { Name = "Product B", Price = 25.50m, Quantity = 1 }
    ]
};

// 3️⃣ Add custom fields to the invoice dynamically
invoice.CustomFields["Purchase Order"] = "PO-12345";
invoice.CustomFields["Salesperson"] = "John Doe";

// 4️⃣ Generate the PDF from the invoice
try {
    byte[] pdfBytes = await invoiceGenerator.GenerateAsync(invoice);
    
    // 5️⃣ Write the PDF out
    var outputPath = Path.Combine(
        Directory.GetCurrentDirectory(),
        "TestInvoice.pdf"
    );
    await File.WriteAllBytesAsync(outputPath, pdfBytes);
    
    Console.WriteLine($"✅ PDF written to {outputPath}");
} catch (Exception ex) {
    Console.WriteLine($"❌ Error generating PDF: {ex.Message}");
}

Step-by-Step Usage

1. Service Registration

Register the required services in your Program.cs or startup class:

using Microsoft.Extensions.DependencyInjection;
using InvoiceGenerator.Core.Extensions;

var services = new ServiceCollection()
    // Basic registration with default options
    .AddInvoiceGenerator()
    .BuildServiceProvider();
    
// Or with custom options
var services = new ServiceCollection()
    .AddInvoiceGenerator(options => {
        // Configure PDF options using string constants
        options.DefaultPageSize = InvoiceGeneratorOptions.PageSizes.A4;
        options.DefaultOrientation = InvoiceGeneratorOptions.Orientations.Portrait;
        options.DefaultMarginMm = 15;
        options.DefaultDocumentTitle = "Invoice Generator";
        
        // Optional: Set a custom template path
        // options.CustomTemplatePath = "CustomInvoiceTemplate";
        
        // Optional: Provide an IronPdf license key
        // options.IronPdfLicenseKey = "YOUR-LICENSE-KEY";
    })
    .BuildServiceProvider();
2. PDF Generation

The library provides a high-level IInvoiceGenerator interface and InvoicePdfGenerator implementation that simplifies the PDF generation process:

using InvoiceGenerator.Core.Services;
using InvoiceGenerator.Core.Contracts;

// Resolve the IInvoiceGenerator service from the DI container
var invoiceGenerator = services.GetRequiredService<IInvoiceGenerator>();

// 1. Create your invoice model
var invoice = new Invoice
{
    Number = "INV-001",
    IssuedDate = DateTime.Today,
    DueDate = DateTime.Today.AddDays(30),
    SellerAddress = new Address
    {
        CompanyName = "ACME Corp",
        Street = "123 Main St",
        City = "Metropolis",
        State = "NY",
        Email = "sales@acme.com",
    },
    CustomerAddress = new Address
    {
        CompanyName = "Wayne Enterprises",
        Street = "456 Oak Ave",
        City = "Gotham",
        State = "NJ",
        Email = "wayne@example.com",
    },
    LineItems =
    [
        new() { Name = "Product A", Price = 10.00m, Quantity = 2 },
        new() { Name = "Product B", Price = 25.50m, Quantity = 1 }
    ]
};

// 2. Add custom fields to the invoice (optional)
invoice.CustomFields["Purchase Order"] = "PO-12345";
invoice.CustomFields["Salesperson"] = "John Doe";
invoice.CustomFields["Terms"] = "Net 30";

// 3. Generate the PDF directly from the invoice model
byte[] pdfBytes = await invoiceGenerator.GenerateAsync(invoice);

// 4. Save the PDF file
var outputPath = Path.Combine(Directory.GetCurrentDirectory(), "MyInvoice.pdf");
await File.WriteAllBytesAsync(outputPath, pdfBytes);

Console.WriteLine($"PDF generated successfully at {outputPath}");
Using the Lower-Level Components

Alternatively, you can use the lower-level components directly for more control:

using InvoiceGenerator.Core.Services;

// Resolve services from the DI container
var razorRenderer = services.GetRequiredService<IRazorViewToStringRenderer>();
var pdfGenerator = services.GetRequiredService<IPdfGenerator>();

// 1. Create a model for your view
var invoiceModel = new Invoice(); // Your data model

// 2. Render the Razor view to an HTML string
string html = await razorRenderer.RenderViewToStringAsync(
    "Views/InvoiceReport.cshtml", 
    invoiceModel
);

// 3. Generate the PDF from the HTML string
byte[] pdfBytes = pdfGenerator.GeneratePdf(html);

// 4. Save the PDF file
var outputPath = Path.Combine(Directory.GetCurrentDirectory(), "MyInvoice.pdf");
await File.WriteAllBytesAsync(outputPath, pdfBytes);

Console.WriteLine($"PDF generated successfully at {outputPath}");

Project Structure

The InvoiceGenerator.Core library is designed with simplicity in mind, using a consolidated approach for configuration and service registration:

  • ServiceCollectionExtensions.cs: Contains the main extension methods for registering services and the InvoiceGeneratorOptions class with all configuration options
  • Contracts/: Contains the data models like Invoice, Address, and LineItem
  • Services/: Contains the service implementations for invoice generation and PDF creation
  • Views/: Contains the Razor templates used for rendering invoices

Contributing

Contributions are welcome! If you'd like to contribute, please follow these steps:

  1. Fork the repository on GitHub.
  2. Create a new branch for your feature or bug fix.
  3. Make your changes and commit them with a clear message.
  4. Push your branch to your fork.
  5. Open a pull request to the main repository.

License

This project is licensed under the MIT License. See the LICENSE file for more details.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.1.3 148 6/29/2025
2.1.2 88 6/28/2025
2.1.1 95 6/28/2025
2.1.0 109 6/28/2025
2.0.4 140 6/25/2025
2.0.3 141 6/25/2025
2.0.2 139 6/24/2025
2.0.1 143 6/24/2025
2.0.0 147 6/17/2025