Skip to main content

Create an invoice

Create an invoice

An invoice brings together structured data, branding, and an item table that can span several pages. Use the DynamicPDF Flow API to turn sample billing data into a paginated invoice. The example follows CreateInvoice.cs and saves the result as CreateInvoice_output.pdf.

Fluent recipe / 23Create an invoiceGenerate a paginated invoice with billing addresses, itemized charges, and a grand total.

What you’ll create​

  • A Letter-sized invoice with a centered invoice number and a logo at the upper right of the first page.
  • Issue and due dates, plus side-by-side seller and customer addresses.
  • A table of 40 produce items with right-aligned amounts and column headings that repeat on continuation pages.
  • A grand total of $1,459.28 for the supplied data, payment notes, and a footer with the current and total page numbers.
Sample invoice with billing addresses and an itemized produce table.

Example code​

Add the following class to a console project that references the DynamicPDF Flow API. See the quick start for an overview. Ensure InvoiceProduce.json and DPDFLogo.png are in the Resources folder.

using System.Globalization;
using System.Text.Json;
using DynamicPDF.Flow;

namespace FluentExamples.Examples;

internal static class CreateInvoice
{
private static readonly CultureInfo InvoiceCulture =
CultureInfo.GetCultureInfo("en-US");

public static void Run(string outputRoot)
{
var invoice = CreateSampleInvoice();
var path = Path.Combine(
outputRoot, "CreateInvoice_output.pdf");
var numbering = PageNumberingStyle.Numeric;
var resources = Path.Combine(
AppContext.BaseDirectory, "Resources");
var logoPath = Path.Combine(resources, "DPDFLogo.png");

DocumentBuilder.Create()
.Title($"Invoice {invoice.Number}")
.Style("""
text {
font-family: Helvetica;
font-size: 10pt;
color: #182538;
}
.heading {
font-weight: bold;
color: #193d6c;
background-color: #edf3fa;
padding: 6pt;
}
.line {
padding: 5pt 6pt;
border-bottom: 0.5pt solid #dce4ed;
}
.number {
text-align: right;
}
.notes {
padding: 10pt;
background-color: #edf3fa;
}
""")
.Pages(page =>
{
page.Size(PageSize.Letter)
.Margins(50, LengthUnit.Point)
.Footer(footer => footer
.Height(24, LengthUnit.Point)
.Center(footer.CurrentPage(numbering)
+ " / "
+ footer.TotalPages(numbering)))
.Table(table => table
.Columns(columns => columns
.FixedWidth(42, LengthUnit.Point)
.RelativeWidth()
.FixedWidth(
42, LengthUnit.Point))
.Row(row => row
.Cell("")
.Cell(cell => cell.Text(
$"Invoice {invoice.Number}",
text => text
.Align(TextAlign.Center)
.FontSize(
22, LengthUnit.Point)
.Color("#193d6c")))
.Cell(cell => cell.Image(logoPath,
image => image
.Width(42, LengthUnit.Point)
.Height(
40, LengthUnit.Point)))))
.Spacing(10)
.Text("Issued "
+ FormatDate(invoice.IssueDate)
+ " | Due "
+ FormatDate(invoice.DueDate))
.Spacing(16)
.Table(table => AddAddresses(table, invoice))
.Spacing(20)
.Table(table => AddItems(table, invoice))
.Spacing(12)
.Text("Grand total "
+ Money(invoice.Items.Sum(i => i.Total)),
text => text
.FontSize(14, LengthUnit.Point)
.Align(TextAlign.Right));

if (!string.IsNullOrWhiteSpace(invoice.Notes))
{
page.Spacing(18)
.Text("<b>Payment notes</b><br/>"
+ invoice.Notes, "notes");
}
})
.Save(path);

Console.WriteLine(
$"Created {Path.GetFullPath(path)}");
}

private static void AddAddresses(
TableBuilder table, Invoice invoice)
{
var seller = invoice.Seller;
var customer = invoice.Customer;

table.Columns(columns => columns.RelativeWidth()
.FixedWidth(24, LengthUnit.Point)
.RelativeWidth())
.Header(row => row
.Cell("From", "heading")
.Cell("")
.Cell("Bill to", "heading"))
.RowCells(seller.Company, "", customer.Company)
.RowCells(seller.Street, "", customer.Street)
.RowCells(seller.City, "", customer.City);
}

private static void AddItems(
TableBuilder table, Invoice invoice)
{
table.Columns(columns => columns
.FixedWidth(32, LengthUnit.Point)
.RelativeWidth(3)
.RelativeWidth()
.RelativeWidth()
.RelativeWidth())
.Header(row => row
.Cell("#", "heading")
.Cell("Description", "heading")
.Cell("Unit price", "heading number")
.Cell("Qty", "heading number")
.Cell("Amount", "heading number"));

for (int index = 0; index < invoice.Items.Length;
index++)
{
var item = invoice.Items[index];
table.Row(row => row
.Cell((index + 1).ToString(InvoiceCulture),
"line")
.Cell(item.Description, "line")
.Cell(Money(item.UnitPrice), "line number")
.Cell(item.Quantity.ToString(InvoiceCulture),
"line number")
.Cell(Money(item.Total), "line number"));
}
}

private static string Money(decimal value) =>
value.ToString("C2", InvoiceCulture);

private static string FormatDate(DateOnly date) =>
date.ToString("MMM d, yyyy", InvoiceCulture);

private static Invoice CreateSampleInvoice()
{
var issueDate = new DateOnly(2026, 11, 7);
var seller = new Address("NorthWind Produce",
"333 Northwest Street", "New York, NY 21345");
var customer = new Address("Acme Grocery",
"223 Harbor Street", "Frederick, MD 21703");

var itemsPath = Path.Combine(AppContext.BaseDirectory,
"Resources", "InvoiceProduce.json");
using var input = File.OpenRead(itemsPath);
var items = JsonSerializer.Deserialize<LineItem[]>(
input, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}) ?? throw new InvalidDataException(
"The invoice produce file must contain items.");

return new Invoice("XX-1234", issueDate,
issueDate.AddDays(14), seller, customer, items,
"Include invoice XX-1234 with your payment.");
}

private sealed record Invoice(
string Number, DateOnly IssueDate, DateOnly DueDate,
Address Seller, Address Customer, LineItem[] Items,
string? Notes);

private sealed record Address(
string Company, string Street, string City);

private sealed record LineItem(
string Description, decimal UnitPrice, int Quantity)
{
public decimal Total => UnitPrice * Quantity;
}
}
Imports System.IO
Imports System.Globalization
Imports System.Text.Json
Imports DynamicPDF.Flow

Friend Module CreateInvoice
Private ReadOnly InvoiceCulture As CultureInfo =
CultureInfo.GetCultureInfo("en-US")

Public Sub Run(outputRoot As String)
Dim invoice = CreateSampleInvoice()
Dim outputPath = Path.Combine(
outputRoot, "CreateInvoice_output.pdf")
Dim numbering = PageNumberingStyle.Numeric
Dim resources = Path.Combine(
AppContext.BaseDirectory, "Resources")
Dim logoPath = Path.Combine(resources, "DPDFLogo.png")

DocumentBuilder.Create().
Title($"Invoice {invoice.Number}").
Style("text {
font-family: Helvetica;
font-size: 10pt;
color: #182538;
}
.heading {
font-weight: bold;
color: #193d6c;
background-color: #edf3fa;
padding: 6pt;
}
.line {
padding: 5pt 6pt;
border-bottom: 0.5pt solid #dce4ed;
}
.number {
text-align: right;
}
.notes {
padding: 10pt;
background-color: #edf3fa;
}").
Pages(Sub(page)
page.Size(PageSize.Letter).
Margins(50, unit:=LengthUnit.Point).
Footer(Sub(footer) footer.
Height(24, LengthUnit.Point).
Center(footer.CurrentPage(numbering) &
" / " &
footer.TotalPages(numbering))).
Table(Sub(table) table.
Columns(Sub(columns) columns.
FixedWidth(42, LengthUnit.Point).
RelativeWidth().
FixedWidth(
42, LengthUnit.Point)).
Row(Sub(row) row.
Cell("").
Cell(Sub(cell) cell.Text(
$"Invoice {invoice.Number}",
Sub(text) text.
Align(TextAlign.Center).
FontSize(
22, LengthUnit.Point).
Color("#193d6c"))).
Cell(Sub(cell) cell.Image(logoPath,
Sub(image) image.
Width(42, LengthUnit.Point).
Height(
40, LengthUnit.Point))))).
Spacing(10).
Text("Issued " &
FormatDate(invoice.IssueDate) &
" | Due " &
FormatDate(invoice.DueDate)).
Spacing(16).
Table(Sub(table) AddAddresses(table, invoice)).
Spacing(20).
Table(Sub(table) AddItems(table, invoice)).
Spacing(12).
Text("Grand total " &
Money(invoice.Items.Sum(Function(i) i.Total)),
Sub(text) text.
FontSize(14, LengthUnit.Point).
Align(TextAlign.Right))

If Not String.IsNullOrWhiteSpace(invoice.Notes) Then
page.Spacing(18).
Text("<b>Payment notes</b><br/>" &
invoice.Notes, "notes")
End If
End Sub).
Save(outputPath)

Console.WriteLine(
$"Created {Path.GetFullPath(outputPath)}")
End Sub

Private Sub AddAddresses(table As TableBuilder, invoice As Invoice)
Dim seller = invoice.Seller
Dim customer = invoice.Customer

table.Columns(Sub(columns) columns.RelativeWidth().
FixedWidth(24, LengthUnit.Point).
RelativeWidth()).
Header(Sub(row) row.
Cell("From", "heading").
Cell("").
Cell("Bill to", "heading")).
RowCells(seller.Company, "", customer.Company).
RowCells(seller.Street, "", customer.Street).
RowCells(seller.City, "", customer.City)
End Sub

Private Sub AddItems(table As TableBuilder, invoice As Invoice)
table.Columns(Sub(columns) columns.
FixedWidth(32, LengthUnit.Point).
RelativeWidth(3).
RelativeWidth().
RelativeWidth().
RelativeWidth()).
Header(Sub(row) row.
Cell("#", "heading").
Cell("Description", "heading").
Cell("Unit price", "heading number").
Cell("Qty", "heading number").
Cell("Amount", "heading number"))

For index = 0 To invoice.Items.Length - 1
Dim lineNumber = index + 1
Dim item = invoice.Items(index)
table.Row(Sub(row) row.
Cell(lineNumber.ToString(InvoiceCulture),
"line").
Cell(item.Description, "line").
Cell(Money(item.UnitPrice), "line number").
Cell(item.Quantity.ToString(InvoiceCulture),
"line number").
Cell(Money(item.Total), "line number"))
Next
End Sub

Private Function Money(value As Decimal) As String
Return value.ToString("C2", InvoiceCulture)
End Function

Private Function FormatDate(invoiceDate As DateOnly) As String
Return invoiceDate.ToString("MMM d, yyyy", InvoiceCulture)
End Function

Private Function CreateSampleInvoice() As Invoice
Dim issueDate = New DateOnly(2026, 11, 7)
Dim seller = New Address("NorthWind Produce",
"333 Northwest Street", "New York, NY 21345")
Dim customer = New Address("Acme Grocery",
"223 Harbor Street", "Frederick, MD 21703")

Dim itemsPath = Path.Combine(AppContext.BaseDirectory,
"Resources", "InvoiceProduce.json")
Using input = File.OpenRead(itemsPath)
Dim items = DeserializeItems(input)

Return New Invoice("XX-1234", issueDate,
issueDate.AddDays(14), seller, customer, items,
"Include invoice XX-1234 with your payment.")
End Using
End Function


Private Function DeserializeItems(input As Stream) As LineItem()
Dim options As New JsonSerializerOptions With {
.PropertyNameCaseInsensitive = True
}
Dim items = JsonSerializer.Deserialize(Of LineItem())(input, options)
If items Is Nothing Then
Throw New InvalidDataException(
"The invoice produce file must contain items.")
End If
Return items
End Function

Private NotInheritable Class Invoice
Public ReadOnly Property Number As String
Public ReadOnly Property IssueDate As DateOnly
Public ReadOnly Property DueDate As DateOnly
Public ReadOnly Property Seller As Address
Public ReadOnly Property Customer As Address
Public ReadOnly Property Items As LineItem()
Public ReadOnly Property Notes As String

Public Sub New(number As String,
issueDate As DateOnly,
dueDate As DateOnly,
seller As Address,
customer As Address,
items As LineItem(),
notes As String)
Me.Number = number
Me.IssueDate = issueDate
Me.DueDate = dueDate
Me.Seller = seller
Me.Customer = customer
Me.Items = items
Me.Notes = notes
End Sub
End Class

Private NotInheritable Class Address
Public ReadOnly Property Company As String
Public ReadOnly Property Street As String
Public ReadOnly Property City As String

Public Sub New(company As String,
street As String,
city As String)
Me.Company = company
Me.Street = street
Me.City = city
End Sub
End Class

Private NotInheritable Class LineItem
Public ReadOnly Property Description As String
Public ReadOnly Property UnitPrice As Decimal
Public ReadOnly Property Quantity As Integer

Public Sub New(description As String,
unitPrice As Decimal,
quantity As Integer)
Me.Description = description
Me.UnitPrice = unitPrice
Me.Quantity = quantity
End Sub

Public ReadOnly Property Total As Decimal
Get
Return UnitPrice * Quantity
End Get
End Property
End Class

End Module

How it works​

1. Load the invoice data and choose an output path​

CreateSampleInvoice sets the invoice number, dates, billing addresses, and payment notes. It reads the produce descriptions, unit prices, and quantities from InvoiceProduce.json. Each line item calculates its total by multiplying the unit price by the quantity.

Path.Combine joins outputRoot with CreateInvoice_output.pdf. Make sure the output directory exists.

The document stylesheet defines the text and table styles. A three-column table at the top of the first page centers the invoice number and places the logo in the rightmost cell. The logo aligns with the right edge of the Amount column.

The footer uses CurrentPage and TotalPages to show the current page and total page count.

3. Add dates and billing addresses​

The issue and due dates appear above the address table. AddAddresses uses RowCells to place the seller and customer details side by side, with separate rows for company name, street, and city, state, and ZIP code.

4. Add the produce items and total​

AddItems defines five columns and adds a row for each JSON record. Flow repeats the table header when the rows continue on another page. The example formats prices in US dollars and aligns numeric cells to the right.

After the table, the example sums the line totals and adds payment notes when present.

5. Save the invoice​

.Save(path) writes the PDF to outputRoot. Saving overwrites an existing file with the same name. The example prints the full output path after saving.

Next steps​

See Add a table for a smaller table example and Add page numbers for more footer options.