5. Creating PDF invoices (Basic profile)

To create a ZUGFeRD invoice, we now have to combine what we've learned in chapter 2 "Creating PDF/A files with iText" with what we've learned in chapter 4 "Creating XML Invoices with iText".

Creating PDF from scratch

In this chapter, we'll discuss a single example: PdfInvoicesBasic. In this example we'll create a PDF document for every invoice stored in our database. The PDF documents will be ZUGFeRD invoices using the Basic profile.

Let's start with the different constants defined in this class:

public static final String DEST = "results/zugferd/pdf/basic%05d.pdf";
public static final String ICC = "resources/color/sRGB_CS_profile.icm";
public static final String REGULAR = "resources/fonts/OpenSans-Regular.ttf";
public static final String BOLD = "resources/fonts/OpenSans-Bold.ttf";
public static final String NEWLINE = "\n";

We recognize the pattern for the destination files, the color profile (as discussed in chapter 2), two font files, and a string with a newline character.

The main method of this example is very straightforward:

public static void main(String[] args)
    throws IOException, ParserConfigurationException, SQLException,
        SAXException, TransformerException, ParseException
        DataIncompleteException, InvalidCodeException {
        + "/itextkey-html2pdf_typography.xml");
    File file = new File(DEST);
    PdfInvoicesBasic app = new PdfInvoicesBasic();
    PojoFactory factory = PojoFactory.getInstance();
    List invoices = factory.getInvoices();
    for (Invoice invoice : invoices) {

In this method, we create an instance of the PdfInvoicesBasic class; we get a List of Invoice objects from the PojoFactory; for every invoice, we call the createPdf() method.

public void createPdf(Invoice invoice)
    throws ParserConfigurationException, SAXException, TransformerException,
    IOException, ParseException, DataIncompleteException, InvalidCodeException {

    String dest = String.format(DEST, invoice.getId());

    // Create the XML
    InvoiceData invoiceData = new InvoiceData();
    IBasicProfile basic = invoiceData.createBasicProfileData(invoice);
    InvoiceDOM dom = new InvoiceDOM(basic);

    // Create the ZUGFeRD document
    ZugferdDocument pdfDocument = new ZugferdDocument(
        new PdfWriter(dest), ZugferdConformanceLevel.ZUGFeRDBasic,
        new PdfOutputIntent("Custom", "", "http://www.color.org",
            "sRGB IEC61966-2.1", new FileInputStream(ICC)));
        "ZUGFeRD invoice", dom.toXML(), "ZUGFeRD-invoice.xml",
        PdfName.ApplicationXml, new PdfDictionary(), PdfName.Alternative);

    // Create the document
    Document document = new Document(pdfDocument);
    document.setFont(PdfFontFactory.createFont(REGULAR, true))
    PdfFont bold = PdfFontFactory.createFont(BOLD, true);

    // Add the header
        new Paragraph()
            .add(new Text(String.format("%s %s\n", basic.getName(), basic.getId()))
            .add(convertDate(basic.getDateTime(), "MMM dd, yyyy")));
    // Add the seller and buyer address
    document.add(getAddressTable(basic, bold));
    // Add the line items
    document.add(getLineItemTable(invoice, bold));
    // Add the grand totals
        basic.getTaxBasisTotalAmount(), basic.getTaxTotalAmount(),
        basic.getGrandTotalAmount(), basic.getGrandTotalAmountCurrencyID(),
        basic.getTaxTypeCode(), basic.getTaxApplicablePercent(),
        basic.getTaxBasisAmount(), basic.getTaxCalculatedAmount(),
        basic.getTaxCalculatedAmountCurrencyID(), bold));
    // Add the payment info


This createPdf() method consists of different parts:

  • We construct a file name (line 5) and we use the InvoiceData class (line 8) that was discussed in chapter 4 to create an IBasicProfile instance (line 9). We use this IBasicProfile instance to create an InvoiceDOM object (line 8). InvoiceDOM is one of the classes available in the pdfInvoice add-on.

  • We construct a ZugferdDocument instance (line 13) and we set the conformance level to ZUGFeRDBasic for the basic profile (line 14). We also add the output intent (line 15-16). We add the XML invoice as an attachment (line 17-19).

  • Then we create the document (line 22), and we add the content: a header (line 28-34), the address information of the seller and the buyer (line 36), the line items (line 38), the grand total and the tax information (line 40-45), and the payment information (line 47-49).

We create the header paragraph in the createPdf() method (lines 28-34), but we're using helper methods for the other content. Let's take a closer look at those methods.

Adding the seller and buyer addresses

Creating a PDF from scratch using iText is easy, but not trivial. It's easy, because you can use many different high-level objects, but it's not trivial as you have to create a design by writing code. In chapter 7, we'll see an alternative way to create PDF invoices that doesn't require you to write much code.

Most of the data that needs to be rendered is available through the IBasicProfile interface. See for instance the getAddressTable() method:

public Table getAddressTable(IBasicProfile basic, PdfFont bold) {
    Table table = new Table(new UnitValue[]{
        new UnitValue(UnitValue.PERCENT, 50),
        new UnitValue(UnitValue.PERCENT, 50)})
        basic.getSellerTaxRegistrationSchemeID(), bold));
        basic.getBuyerTaxRegistrationSchemeID(), bold));
    return table;

We create a table with two columns, and we use convenience methods to create the Cell instances:

public Cell getPartyAddress(String who, String name,
    String line1, String line2, String countryID,
    String postcode, String city, PdfFont bold) {
    Paragraph p = new Paragraph()
        .add(new Text(who).setFont(bold)).add(NEWLINE)
        .add(String.format("%s-%s %s", countryID, postcode, city));
    Cell cell = new Cell()
    return cell;
public Cell getPartyTax(String[] taxId, String[] taxSchema, PdfFont bold) {
    Paragraph p = new Paragraph()
        .add(new Text("Tax ID(s):").setFont(bold));
    if (taxId.length == 0) {
        p.add("\nNot applicable");
    else {
        int n = taxId.length;
        for (int i = 0; i 

With these helper methods, we already have the "upper part" of the invoice as shown in Figure 5.1.

Figure 5.1

Figure 5.1: first part of the invoice

We'll also use a Table to render the invoice lines.

Adding invoice lines

The part with the invoice lines is a Table with six columns that is created like this:

public Table getLineItemTable(Invoice invoice, PdfFont bold) {
    Table table = new Table(
        new UnitValue[]{
            new UnitValue(UnitValue.PERCENT, 43.75f),
            new UnitValue(UnitValue.PERCENT, 12.5f),
            new UnitValue(UnitValue.PERCENT, 6.25f),
            new UnitValue(UnitValue.PERCENT, 12.5f),
            new UnitValue(UnitValue.PERCENT, 12.5f),
            new UnitValue(UnitValue.PERCENT, 12.5f)})
    table.addHeaderCell(createCell("Item:", bold));
    table.addHeaderCell(createCell("Price:", bold));
    table.addHeaderCell(createCell("Qty:", bold));
    table.addHeaderCell(createCell("Subtotal:", bold));
    table.addHeaderCell(createCell("VAT:", bold));
    table.addHeaderCell(createCell("Total:", bold));
    Product product;
    for (Item item : invoice.getItems()) {
        product = item.getProduct();
                item.getCost() + ((item.getCost() * product.getVat()) / 100))))
    return table;

Again we use some helper methods to create Cell objects:

public Cell createCell(String text) {
    return new Cell().setPadding(0.8f)
        .add(new Paragraph(text)
public Cell createCell(String text, PdfFont font) {
    return new Cell().setPadding(0.8f)
        .add(new Paragraph(text)

The result looks like figure 5.2:

Figure 5.2

Figure 5.2: rendering the line items of an invoice

We need yet another table for the tax totals and the grand total.

Adding the totals

We add a table with all the totals like this:

public Table getTotalsTable(String tBase, String tTax, String tTotal,
    String tCurrency, String[] type, String[] percentage, String base[],
    String tax[], String currency[], PdfFont bold) {
    Table table = new Table(
        new UnitValue[]{
            new UnitValue(UnitValue.PERCENT, 8.33f),
            new UnitValue(UnitValue.PERCENT, 8.33f),
            new UnitValue(UnitValue.PERCENT, 25f),
            new UnitValue(UnitValue.PERCENT, 25f),
            new UnitValue(UnitValue.PERCENT, 25f),
            new UnitValue(UnitValue.PERCENT, 8.34f)})
    table.addCell(createCell("TAX:", bold));
    table.addCell(createCell("%", bold)
    table.addCell(createCell("Base amount:", bold));
    table.addCell(createCell("Tax amount:", bold));
    table.addCell(createCell("Total:", bold));
    table.addCell(createCell("Curr.:", bold));
    int n = type.length;
    for (int i = 0; i 

The code is very similar to what we did for the line items table. The only thing that is out of the ordinary, is that we create a cell that spans two columns in line 24-25. Figure 5.3 shows the result.

Figure 5.3

Figure 5.3: rendering the totals

We're almost there. There only one piece of content missing.

Adding the payment info

Adding the payment info is just a matter of creating a Paragraph:

public Paragraph getPaymentInfo(String ref, String[] bic, String[] iban) {
    Paragraph p = new Paragraph(String.format(
        "Please wire the amount due to our bank account using "
        + " the following reference: %s",
    int n = bic.length;
    for (int i = 0; i 

Note that we made some assumptions about the payment means. ZUGFeRD allows for different payment types, but we assumed that payments have to be done by bank wire. The result is shown in figure 5.4:

Figure 5.4

Figure 5.4: payment info

In the createPdf() method, we combined all this content with a PDF invoice as result.

The final result

The goal of this example was to create a proof of concept, and Figure 5.5 shows the final result.

Figure 5.5

Figure 5.5: the resulting invoice

People who want to process the invoice manually, can do so; if they don't open the attachment panel, they won't even notice that there's an XML attachment inside. People who want to process the invoice automatically, can extract the XML or have their software extract the XML for processing.

I am aware that this invoice doesn't look very sexy. We could create tables with rounded borders, introduce a logo and some colors, we could add an extra sheet with terms-of-use, and so on, but that would lead us too far. In chapter 7, we'll discover that there is an alternative way to create PDF invoices, but let's take a look at some HTML first.

Share this article

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now