iText pdf library
Website search

7. Creating PDF invoices (Comfort)

Converting XML to HTML, and HTML to PDF

Please take a look at the PdfInvoicesComfort example. We'll reuse some of the code from the example in chapter 6, but instead of merely a createHtml() method, we'll now call a createPdf() method:

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

That createPdf() method will create an HTML file first, and then convert it to PDF:

public void createPdf(Invoice invoice, FileOutputStream fos)
    throws IOException, ParserConfigurationException,
    SAXException, TransformerException,
    DataIncompleteException, InvalidCodeException {
    IComfortProfile comfort =
        new InvoiceData().createComfortProfileData(invoice);
    InvoiceDOM dom = new InvoiceDOM(comfort);
    StreamSource xml = new StreamSource(
        new ByteArrayInputStream(dom.toXML()));
    StreamSource xsl = new StreamSource(new File(XSL));
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(xsl);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer htmlWriter = new OutputStreamWriter(baos);
    transformer.transform(xml, new StreamResult(htmlWriter));
    byte[] html = baos.toByteArray();

    ZugferdDocument pdfDocument = new ZugferdDocument(
        new PdfWriter(fos), ZugferdConformanceLevel.ZUGFeRDComfort,
        new PdfOutputIntent("Custom", "", "",
            "sRGB IEC61966-2.1", new FileInputStream(INTENT)));
        "ZUGFeRD invoice", dom.toXML(), "ZUGFeRD-invoice.xml",
        PdfName.ApplicationXml, new PdfDictionary(), PdfName.Alternative);

        new ByteArrayInputStream(html), pdfDocument, getProperties());

The body of this method consists of three parts:

  • Line 5-18 are copied from the createHtml() method we created in the previous chapter, but as you can see in line 19, we don't create an HTML file that is stored on disk. Instead, we keep the HTML in memory.

  • Line 21-28 start the same way as our example in chapter 5. We create a ZugferdDocument and we add the XML as an attachment. The line where we tell iText to tag the document isn't strictly necessary, but it's good practice.

  • Line 30-31 is new: in chapter 5, we created Paragraph and Table objects, and we added those object to a Document instance. In this case, we'll leave the creation of building blocks to the pdfHTML add-on. The add-on will convert the content of  <p> tags to Paragraph objects, the content of  <table> tags to the [blockcode] Table  objects, and so on.

There are a couple of caveats, though. As we created the HTML in memory, the relative links to resources such as images and CSS can't be resolved. That's why we define a ConverterProperties instance. That instance is obtained through the getProperties() method:

public ConverterProperties getProperties() {
    if (properties == null) {
        properties = new ConverterProperties().setBaseUri("resources/zugferd/");
    return properties;

In the converter properties, we define a base URI. The resources/zugferd/ directory contains the logo.png and the invoice.css file. Without the base URI, the HTML to PDF conversion process would never know where to look for ./logo.png or ./css.html.

The ConverterProperties object can also be used to define other properties, such as the FontProvider. All ZUGFeRD documents are also PDF/A document, which means that all fonts need to be embedded. In this case, we used FreeSans as font, as defined in the first line of our CSS file: body { font-family: FreeSans; } Different fonts of the FreeSans font family are shipped with the pdfHTML add-on, and the default FontProvider knows where to find that font. If you want to use another font, you may need to create a custom FontProvider that tells iText where to find the fonts you need.

The final result

Figure 7.1 shows the resulting PDF. It looks much nicer than the invoices we produced in chapter 5, doesn't it?

Figure 7.1

Figure 7.1: a ZUGFeRD invoice created from HTML

If you look at the panel to the left, you can see the effect of the extra line we smuggled into our code (pdfDocument.setTagged();). As a result, the invoice is now also accessible. The HTML tables can now also be interpreted as tables by a PDF processor that understands tagged PDF. This is an example of a future-proof, archivable invoice that can be read by humans (including people who are visually impaired) as well as by machines.

Before we close, let's also take a look inside the PDF document. In figure 7.2, we see the root object of the PDF document, aka the catalog. We also see the /AF(Associated Files) and the /Names entry. We recognize the/EmbeddedFiles name tree that has a single element named "ZUGFeRD invoice". This refers to a dictionary of filetype /Filespec that is also referred to from the /AF array. The /AFRelationship is "Altermative", meaning that the PDF document and the attached XML are alternative presentations of the same content. This is required by the ZUGFeRD standard.

Figure 7.2

Figure 7.2: The Associated File

Figure 7.3 shows the XMP metadata. The document knows that it's a PDF/A-3B document because of the presence of pdfaid:part="3" andpdfaid:conformance="B" attributes in the rdf:Description. There are also a number of entries in the zf namespace, that define the profile (zf:ConformanceLevel = "COMFORT"), the name of the XML attachment (zf:DocumentFileName = "ZUGFeRD-invoice.xml"), the document type (zf:DocumentType = "INVOICE"), and the version of the XML schema for the invoice data (zf:Version = "1.0").


Fiture 7.3

Figure 7.3: The XMP Metadata

You don't have to worry about these Metadata values or the embedded XMP stream. The pdfInvoice add-on automatically takes care of creating this metadata.

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