Modern invoices and delivery notes aren't only read with the eyes. A QR code on the invoice lets you check from your phone that it's genuine and that its data matches what was registered; a barcode with the delivery note number lets the customer's warehouse record the delivery with a scanner in a second. PDFBox can't generate either of them: it draws rectangles, but it doesn't know the encoding rules of a QR code or a Code 128. In this lesson you'll use ZXing, the go-to Java library for barcodes, to calculate the module matrix, and you'll draw it in the PDF in two ways: as an image and, better still, as vector rectangles, sharp at any size. You'll learn what the quiet zone and the error correction level are, what minimum size a code needs to scan reliably and how to check it automatically. Everything will end up in the PdfCodes class.

Contents

  1. PDFBox doesn't generate codes: the role of ZXing
  2. Adding ZXing to the project
  3. Key concepts: modules, matrix, quiet zone and size
  4. The QR code: versions and error correction level
  5. Code 128 and other linear symbologies
  6. Image or vectors?
  7. The PdfCodes class
  8. Example: verification QR code and delivery note Code 128
  9. Checking that the codes scan
  10. Verification QR codes on invoices: a note on regulations

PDFBox doesn't generate codes: the role of ZXing

Generating a barcode involves two very different steps:

flowchart LR
    D["Data<br/>'A-2026-0001'"] --> Z["ZXing<br/>encoding:<br/>character set,<br/>check digits,<br/>error correction"]
    Z --> M["BitMatrix<br/>module matrix<br/>true = dark"]
    M --> P1["PDFBox: rectangles<br/>(vector)"]
    M --> P2["BufferedImage →<br/>LosslessFactory<br/>(image)"]
  1. Encoding: converting the data into a pattern of bars or squares according to a standard (ISO/IEC 18004 for QR, ISO/IEC 15417 for Code 128). It's complex: character tables, check digits, Reed-Solomon codes for error correction, masks... This is handled by ZXing (Zebra Crossing), an open-source library maintained for years and used on millions of devices.
  2. Drawing: painting that pattern in the PDF. This is pure module 2: filled rectangles (lesson 02-05) or an image (lesson 02-06).

ZXing returns the pattern as a BitMatrix: a grid of bits where true means "dark module". With that, the rest is work you already know how to do.

Adding ZXing to the project

ZXing is published as two artifacts:

Artifact Contents Do we need it?
com.google.zxing:core Encoders and decoders for all symbologies; depends only on the JDK Yes
com.google.zxing:javase Java SE utilities: MatrixToImageWriter (matrix → BufferedImage), BufferedImageLuminanceSource (for reading codes from an image) Yes, for the image variant and for the scan tests

Add to pom.xml, inside <dependencies> (centralising the version in a property, as we did with PDFBox):

<properties>
    <!-- ... the previous properties ... -->
    <zxing.version>3.5.4</zxing.version>
</properties>

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>${zxing.version}</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>${zxing.version}</version>
</dependency>

With mvn dependency:tree you'll see that javase pulls in two more dependencies (jcommander, for its command-line tool, and jai-imageio-core). If you're only going to draw vectors, core is enough; turning a BitMatrix into a BufferedImage takes six lines of code, as you'll see in the common mistakes. Always use the latest stable version of the 3.5 branch.

Key concepts: modules, matrix, quiet zone and size

Concept What it is Typical value
Module The smallest unit of the code: a bar or space of width 1 (linear) or a small square (QR) —
X dimension Physical size of a module on paper Code 128: 0.25-0.50 mm. QR: ≥ 0.4 mm for phones
Quiet zone Blank margin around the code that the reader needs in order to know where it starts QR: 4 modules per side. Code 128: 10 modules (or 6.4 mm) on each side
Bar height In linear codes, the height of the bars ≥ 15% of the code's width, or about 10-15 mm
Contrast Dark modules on a light background Black on white; never the other way round, nor light colours

Two practical consequences:

  • The quiet zone is part of the code. If you put a QR code right up against the edge of a blue box or some text, many readers won't scan it. Our method will draw a white background that includes the quiet zone, to guarantee it even when there's colour underneath.
  • The minimum size depends on the modules. A QR code with more data has more modules; at the same size on paper, each module is smaller and harder to read. That's why a QR code's URL should be short.

The QR code: versions and error correction level

A QR code grows in versions: version 1 has 21 × 21 modules, version 2 has 25 × 25, and each version adds 4 modules per side up to version 40 (177 × 177). ZXing automatically chooses the smallest version that the data fits into.

In addition, a QR code includes redundant information (Reed-Solomon) that lets it be read even when it's partially damaged: smudged, creased or with a staple on top. The more redundancy, the more modules:

Level Recovers up to Typical use
L (low) ~7% Screens, clean environments
M (medium) ~15% Printed documents (a sensible default)
Q (quartile) ~25% Industrial environments, labels that get dirty
H (high) ~30% When a logo is overlaid on the QR code

For our verification URL (about 90 characters) ZXing produces these matrices:

Level L: 37 x 37 modules
Level M: 41 x 41 modules
Level Q: 49 x 49 modules
Level H: 53 x 53 modules

With level M and the quiet zone (4 + 41 + 4 = 49 modules), a 25 mm QR code has 0.51 mm modules: perfectly readable with any phone. With level H at 20 mm they'd drop to 0.33 mm and it would start to struggle. We'll use level M.

Code 128 and other linear symbologies

Code 128 is the most widely used linear barcode in logistics: it encodes the whole of ASCII (letters, numbers and symbols such as the hyphen in "A-2026-0001"), it's compact and it carries a check digit that ZXing calculates for you. It's the right choice for delivery note, order or batch numbers.

Symbology Type Content Common use
Code 128 Linear Full ASCII Delivery notes, internal logistics, shipping labels
EAN-13 Linear 13 digits (with check digit) Retail products (requires codes assigned by GS1)
Code 39 Linear Capitals, digits and a few symbols Legacy systems; less compact
QR Code 2D Text, URL, binary Document verification, links, payments
Data Matrix 2D Text, binary Marking small parts, pharmaceutical sector
PDF417 Stacked 2D Text, binary Boarding passes, identity documents

All of them are generated with ZXing by changing the writer class (Code128Writer, EAN13Writer, QRCodeWriter, DataMatrixWriter, PDF417Writer), and all of them return a BitMatrix. The drawing is always the same.

Image or vectors?

As an image (LosslessFactory) As vectors (rectangles)
Sharpness Depends on the pixels; when zoomed in or printed at another scale the edges soften Perfect at any scale
Size Lossless image (small, but grows with resolution) A few KB of operators
Code MatrixToImageWriter + LosslessFactory A loop over the matrix
Risks Never JPEG: compression artefacts blur the edges. Scaling with interpolation produces greys No particular risks
PDF/A No problems No problems

A thermal label printer or a warehouse scanner is very sensitive to fuzzy edges. That's why the preferred option is to draw the modules as rectangles: the PDF stores the exact geometry and each printer rasterises it at its own resolution. Even so, we'll also implement the image version, which is useful if the code is going to be reused outside the PDF.

An efficiency detail: a 41 × 41 QR code has hundreds of dark modules. Instead of one rectangle per module, we'll merge the consecutive dark modules in each row into a single rectangle (run-length), and fill them all with a single fill(). In a Code 128, each thick bar thus becomes a single rectangle.

The PdfCodes class

package com.invoicelab.pdf;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

/**
 * QR codes and Code 128 in PDF. ZXing calculates the module matrix; here we draw it
 * as vector rectangles (sharp at any scale) or, if preferred, as an image.
 */
public final class PdfCodes {

    /** Minimum QR quiet zone, in modules. */
    public static final int QR_QUIET_ZONE = 4;
    /** Minimum Code 128 quiet zone, in modules (on each side). */
    public static final int CODE128_QUIET_ZONE = 10;

    private PdfCodes() {
    }

    // ------------------------------------------------------------------ matrices (ZXing)

    /** QR matrix WITHOUT margin: one bit per module (true = dark module). */
    public static BitMatrix qrMatrix(String content, ErrorCorrectionLevel level) {
        Map<EncodeHintType, Object> hints = Map.of(
                EncodeHintType.ERROR_CORRECTION, level,
                EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name(),
                EncodeHintType.MARGIN, 0);                     // we add the quiet zone ourselves
        try {
            // width and height 0: ZXing returns the minimum size, 1 bit = 1 module
            return new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, 0, 0, hints);
        } catch (WriterException e) {
            throw new IllegalArgumentException("Cannot encode the QR code: " + e.getMessage(), e);
        }
    }

    /** Code 128 matrix WITHOUT margin: one row, one bit per module. */
    public static BitMatrix code128Matrix(String content) {
        try {
            return new Code128Writer().encode(content, BarcodeFormat.CODE_128, 0, 1,
                    Map.of(EncodeHintType.MARGIN, 0));
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Cannot encode as Code 128: " + content, e);
        }
    }

    // ------------------------------------------------------------------ vector drawing

    /**
     * Draws a square QR code with side "side" (quiet zone included) with its top-left
     * corner at (x, yTop). Returns the height used (= side).
     */
    public static float drawQr(PDPageContentStream content, String data, ErrorCorrectionLevel level,
                               float x, float yTop, float side) throws IOException {
        BitMatrix m = qrMatrix(data, level);
        int totalModules = m.getWidth() + 2 * QR_QUIET_ZONE;
        float module = side / totalModules;
        // White background: guarantees the quiet zone even if there's colour underneath
        Shapes.drawBox(content, x, yTop - side, side, side, 0, Color.WHITE, null, 0);
        float x0 = x + QR_QUIET_ZONE * module;
        float y0 = yTop - QR_QUIET_ZONE * module;
        drawModules(content, m, x0, y0, module, module);
        return side;
    }

    /**
     * Draws a Code 128 with bars of "height" and the given module width (recommended
     * minimum: 0.25-0.33 mm). Includes the quiet zone. Returns the total width used.
     */
    public static float drawCode128(PDPageContentStream content, String data, float x, float yTop,
                                    float moduleWidth, float height) throws IOException {
        BitMatrix m = code128Matrix(data);
        float totalWidth = (m.getWidth() + 2 * CODE128_QUIET_ZONE) * moduleWidth;
        Shapes.drawBox(content, x, yTop - height, totalWidth, height, 0, Color.WHITE, null, 0);
        drawModules(content, m, x + CODE128_QUIET_ZONE * moduleWidth, yTop, moduleWidth, height);
        return totalWidth;
    }

    /** Total width (quiet zone included) a Code 128 will take up. */
    public static float code128Width(String data, float moduleWidth) {
        return (code128Matrix(data).getWidth() + 2 * CODE128_QUIET_ZONE) * moduleWidth;
    }

    /**
     * Walks through the matrix row by row and merges consecutive dark modules into a single
     * rectangle (far fewer operators than one rectangle per module). A single fill() at the end.
     */
    private static void drawModules(PDPageContentStream content, BitMatrix m, float x0, float yTop,
                                    float moduleWidth, float moduleHeight) throws IOException {
        content.saveGraphicsState();
        content.setNonStrokingColor(Color.BLACK);
        for (int row = 0; row < m.getHeight(); row++) {
            float yRow = yTop - (row + 1) * moduleHeight;          // row 0 is the top one
            int col = 0;
            while (col < m.getWidth()) {
                if (!m.get(col, row)) {
                    col++;
                    continue;
                }
                int start = col;
                while (col < m.getWidth() && m.get(col, row)) {
                    col++;
                }
                content.addRect(x0 + start * moduleWidth, yRow, (col - start) * moduleWidth, moduleHeight);
            }
        }
        content.fill();
        content.restoreGraphicsState();
    }

    // ------------------------------------------------------------------ alternative: image

    /**
     * QR code as a lossless image (LosslessFactory). pixelsPerModule is an integer so that no
     * modules end up a different size. Draw it with drawImage at the desired size.
     */
    public static PDImageXObject qrAsImage(PDDocument document, String data, ErrorCorrectionLevel level,
                                           int pixelsPerModule) throws IOException {
        BitMatrix m = qrMatrix(data, level);
        int side = (m.getWidth() + 2 * QR_QUIET_ZONE) * pixelsPerModule;
        try {
            BitMatrix scaled = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, side, side,
                    Map.of(EncodeHintType.ERROR_CORRECTION, level,
                            EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name(),
                            EncodeHintType.MARGIN, QR_QUIET_ZONE));
            BufferedImage image = MatrixToImageWriter.toBufferedImage(scaled);
            return LosslessFactory.createFromImage(document, image);
        } catch (WriterException e) {
            throw new IllegalArgumentException("Cannot encode the QR code: " + e.getMessage(), e);
        }
    }
}

Explanation, piece by piece:

  • EncodeHintType are ZXing's options. ERROR_CORRECTION sets the level; CHARACTER_SET set to UTF-8 allows accented characters in the QR code's content; MARGIN is the quiet zone that ZXing adds. We set it to 0 and manage it ourselves, so that the size the caller asks for is the real size on paper, quiet zone included.
  • Width and height 0 in encode: ZXing returns the minimum matrix, with one bit per module. If you asked for 300 × 300, ZXing would scale the matrix up to pixels, which is what qrAsImage does but not what we want for drawing vectors.
  • ZXing's exceptions are translated: WriterException is checked and not very descriptive for whoever uses the class; we turn it into an IllegalArgumentException with a clear message. A Code 128 with characters outside ASCII (for example the "º" in "Nº") also produces an IllegalArgumentException.
  • The Y axis: in the matrix, row 0 is the top one; in PDF, y grows upwards. That's why yRow = yTop − (row + 1) × moduleHeight: the bottom corner of row 0's rectangle is one module below the top edge. It's the same "thinking from the top" idea as ContentBox.yFromTop.
  • In a Code 128, the vertical "module" is the full height of the bars: the matrix has a single row and we draw it with moduleHeight = height.
  • drawQr returns the height used and drawCode128 the width: the QR code is square and is stacked vertically; what you usually need from a barcode in order to align it is its width. code128Width lets you calculate it before drawing (to right-align it, for example).
  • qrAsImage uses a whole number of pixels per module: if each module measured 7.3 pixels, some would have 7 and others 8, and the code would come out irregular.

Example: verification QR code and delivery note Code 128

package com.invoicelab.examples;

// imports: pdf (Alignment, ContentBox, PdfCodes, InvoiceLabFonts, Measures, TextMetrics),
// ZXing (BitMatrix, ErrorCorrectionLevel), java.io, java.nio.file and PDFBox

public class CodesDemo {

    static final String VERIFICATION_URL =
            "https://verifica.example/f?nif=B00000000&num=F-2026-0001&fecha=15-01-2026&importe=1470.85";

    public static void main(String[] args) throws IOException {
        Files.createDirectories(Path.of("output"));
        for (ErrorCorrectionLevel level : ErrorCorrectionLevel.values()) {
            BitMatrix m = PdfCodes.qrMatrix(VERIFICATION_URL, level);
            System.out.printf("Level %s: %d x %d modules%n", level, m.getWidth(), m.getHeight());
        }
        System.out.println("Code 128 'A-2026-0001': " + PdfCodes.code128Matrix("A-2026-0001").getWidth() + " modules");

        try (PDDocument document = new PDDocument()) {
            InvoiceLabFonts fonts = new InvoiceLabFonts(document);
            PDFont normal = fonts.regular();
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);
            ContentBox box = ContentBox.invoice(page.getMediaBox());

            try (PDPageContentStream content = new PDPageContentStream(document, page)) {
                float y = box.top();

                // 1) 25 mm vector QR code (quiet zone included), level M
                float side = Measures.mm(25);
                PdfCodes.drawQr(content, VERIFICATION_URL, ErrorCorrectionLevel.M,
                        box.left(), y, side);
                TextMetrics.writeAligned(content, normal, 7, "Vector QR (25 mm)",
                        box.left() + side / 2, y - side - 9, Alignment.CENTER);

                // 2) The same QR code as a lossless image, drawn at the same size
                PDImageXObject qr = PdfCodes.qrAsImage(document, VERIFICATION_URL,
                        ErrorCorrectionLevel.M, 8);
                float xImage = box.left() + Measures.mm(40);
                content.drawImage(qr, xImage, y - side, side, side);
                TextMetrics.writeAligned(content, normal, 7,
                        "Image QR (" + qr.getWidth() + " px)", xImage + side / 2, y - side - 9, Alignment.CENTER);
                y -= side + Measures.mm(12);

                // 3) Code 128 of the delivery note number, with the human-readable text below
                String deliveryNote = "A-2026-0001";
                float moduleWidth = Measures.mm(0.33);
                float height = Measures.mm(12);
                float width = PdfCodes.drawCode128(content, deliveryNote, box.left(), y, moduleWidth, height);
                TextMetrics.writeAligned(content, normal, 8, deliveryNote,
                        box.left() + width / 2, y - height - 10, Alignment.CENTER);
                System.out.printf("Code 128: %.1f mm wide%n", Measures.toMm(width));
            }
            document.save("output/codes.pdf");
        }
        System.out.printf("PDF size: %,d bytes%n", Files.size(Path.of("output/codes.pdf")));
    }
}
Level L: 37 x 37 modules
Level M: 41 x 41 modules
Level Q: 49 x 49 modules
Level H: 53 x 53 modules
Code 128 'A-2026-0001': 145 modules
Code 128: 54.5 mm wide
PDF size: 11,036 bytes
  • The image QR code is 392 pixels: (41 + 8) modules × 8 pixels. Drawn at 25 mm, that's about 400 dpi, which is enough; even so, zoom both QR codes to 800% in the viewer and you'll see that the vector one stays perfect while the image one softens.
  • The Code 128 for "A-2026-0001" is 145 modules plus 20 of quiet zone: at 0.33 mm per module, 54.5 mm. That's the usual X dimension on labels and documents.
  • The human-readable text below the barcode is a highly recommended practice: if the scanner fails, someone can type in the number.
  • The complete PDF, with an embedded font, two QR codes and a barcode, weighs 11 KB.

Checking that the codes scan

A code that "looks fine" may not scan. The best test is to scan it with a phone, but you can also automate it: render the page to an image with PDFBox (we'll cover this in depth in lesson 06-04) and decode it with ZXing. That way you can include it in the automated tests of module 8:

package com.invoicelab.examples;

// imports: ZXing (BinaryBitmap, DecodeHintType, MultiFormatReader, NotFoundException, Result,
// BufferedImageLuminanceSource, HybridBinarizer, GenericMultipleBarcodeReader),
// java.awt.image.BufferedImage, java.io, java.util.Map, Loader, PDDocument, PDFRenderer

/** Renders each page at 150 dpi and reads every code it finds (scan test). */
public class CheckCodes {

    public static void main(String[] args) throws IOException {
        String path = args.length > 0 ? args[0] : "output/codes.pdf";
        try (PDDocument document = Loader.loadPDF(new File(path))) {
            PDFRenderer renderer = new PDFRenderer(document);
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 150);       // module 6
                BinaryBitmap bitmap = new BinaryBitmap(
                        new HybridBinarizer(new BufferedImageLuminanceSource(image)));
                try {
                    Result[] results = new GenericMultipleBarcodeReader(new MultiFormatReader())
                            .decodeMultiple(bitmap, Map.of(DecodeHintType.TRY_HARDER, Boolean.TRUE));
                    for (Result r : results) {
                        System.out.println("Page " + (i + 1) + ": " + r.getBarcodeFormat() + " -> " + r.getText());
                    }
                } catch (NotFoundException e) {
                    System.out.println("Page " + (i + 1) + ": no readable code");
                }
            }
        }
    }
}
Page 1: QR_CODE -> https://verifica.example/f?nif=B00000000&num=F-2026-0001&fecha=15-01-2026&importe=1470.85
Page 1: CODE_128 -> A-2026-0001
  • Loader.loadPDF loads the generated PDF (lesson 01-04) and PDFRenderer.renderImageWithDPI turns it into a BufferedImage.
  • HybridBinarizer converts the image to black and white robustly; GenericMultipleBarcodeReader looks for several codes in the same image.
  • This test reader isn't guaranteed to find all the codes on a page with several identical ones (here it reads one of the two QR codes, which are identical), but it does guarantee that the ones it finds are readable and that their content is as expected. For a strict test, crop the code's area before decoding.
  • Try drawing the QR code with a 10 mm side, or removing the quiet zone by placing it right against a black box: you'll see it stop scanning.

Verification QR codes on invoices: a note on regulations

In several countries, including Spain, there are systems that require or allow invoices to include a QR code with data the recipient can check on the tax authority's website. This is the case, for example, with the Spanish Tax Agency's VeriFactu system or the TicketBAI system of the Basque Country's regional tax authorities. These systems lay down in detail:

  • The service's exact URL and the parameters it must carry (tax ID, number, date, amount...), with their format.
  • Requirements for the QR code: size, correction level, position on the invoice and the captions that must accompany it.
  • The dates of entry into force and who they affect, which have changed more than once.

In this course we use a fictitious URL (https://verifica.example/...), with a made-up format and for training purposes only. If you have to implement a legally valid QR code, consult the regulations in force and the official technical specifications, and have the implementation reviewed by a tax advisor or a specialist professional. What you do take away from this lesson is the technical part, which is the same for any specification: building the URL from the model's data (encoding the parameters with URLEncoder), generating the QR code with the required correction level, drawing it with its quiet zone at the required size and checking that it scans.

Common Mistakes and Tips

  • Forgetting the quiet zone. This is the most common mistake: the code "is visible" but the reader can't find it. Keep 4 modules for QR and 10 for Code 128 free of any marks.
  • A QR code that's too small or holds too much data. Modules below 0.4 mm are hard to read with a phone. Shorten the content (short URLs, minimal parameters) before reducing the size.
  • Compressing the code with JPEGFactory. JPEG artefacts blur the edges. Vectors or LosslessFactory, always.
  • Scaling an image to a size that isn't a multiple of its modules, or with interpolation: greys and irregular modules appear. That's why we draw vectors.
  • Inverted or low-contrast colours. Light modules on a dark background, or an orange QR code on light blue, can't be read by many readers. Dark on white.
  • Characters outside the code's character set. Code 128 only accepts ASCII: "Nº 1" fails. Validate or normalise the data beforehand.
  • You don't need javase to convert to an image. If you want to avoid its dependencies, the equivalent of MatrixToImageWriter.toBufferedImage is:
BufferedImage image = new BufferedImage(m.getWidth(), m.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
for (int y = 0; y < m.getHeight(); y++) {
    for (int x = 0; x < m.getWidth(); x++) {
        image.setRGB(x, y, m.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);   // opaque black or white
    }
}
  • Tip: with rectangles merged by row, some viewers show very thin light lines between rows when the QR code is zoomed right in (an effect of on-screen anti-aliasing). It doesn't affect printing or scanning; if it bothers you, in a QR code you can also merge the modules vertically, or draw it as an image.

Exercises

  1. Minimum QR side. Write a method float minQrSide(String content, ErrorCorrectionLevel level, double minModuleMm) that returns, in points, the minimum side (quiet zone included) for each module to measure at least minModuleMm. What is it for the verification URL with level M and 0.4 mm modules? And with level H?
  2. EAN-13. Generalise the drawing of linear codes with a public method draw1DCode(PDPageContentStream content, BitMatrix m, float x, float yTop, float moduleWidth, float height, int quietZone) and use it to draw the fictitious EAN-13 8400000000017 with EAN13Writer. (Real EAN codes are assigned by GS1; use only fictitious codes in tests.)
  3. Contact QR code in corporate blue. Generate a QR code with Nebula Distribution's contact details in MECARD format, level Q, with the modules in NebulaColors.BLUE instead of black. Check with CheckCodes that it scans.

Solutions

Solution 1.

static float minQrSide(String content, ErrorCorrectionLevel level, double minModuleMm) {
    int modules = PdfCodes.qrMatrix(content, level).getWidth() + 2 * PdfCodes.QR_QUIET_ZONE;
    return Measures.mm(modules * minModuleMm);
}

With level M: (41 + 8) × 0.4 = 19.6 mm. With level H: (53 + 8) × 0.4 = 24.4 mm. Going from level M to H costs almost 5 mm per side. This calculation is useful for validating in the generator that nobody configures a QR code smaller than what's readable.

Solution 2. The drawing loop is made public, adding the white background with the quiet zone:

public static float draw1DCode(PDPageContentStream content, BitMatrix m, float x, float yTop,
                               float moduleWidth, float height, int quietZone) throws IOException {
    float totalWidth = (m.getWidth() + 2 * quietZone) * moduleWidth;
    Shapes.drawBox(content, x, yTop - height, totalWidth, height, 0, Color.WHITE, null, 0);
    drawModules(content, m, x + quietZone * moduleWidth, yTop, moduleWidth, height);
    return totalWidth;
}

// Usage:
BitMatrix ean = new EAN13Writer().encode("8400000000017", BarcodeFormat.EAN_13, 0, 1,
        Map.of(EncodeHintType.MARGIN, 0));                          // 95 modules
PdfCodes.draw1DCode(content, ean, box.left(), y, Measures.mm(0.33), Measures.mm(20), 11);

drawCode128 can now be rewritten in one line by calling draw1DCode with CODE128_QUIET_ZONE. EAN-13 always has 95 modules; its quiet zone is 11 modules on the left and 7 on the right (using 11 on both sides is safe). The last digit (7) is the check digit: if you pass a code with the wrong digit, EAN13Writer throws IllegalArgumentException.

Solution 3. Add a colour parameter (for example, an overload of drawQr that passes it on to drawModules instead of Color.BLACK):

String contact = "MECARD:N:Nebula Distribution Ltd.;TEL:976000000;"
        + "EMAIL:[email protected];URL:https://www.nebula.example;;";
PdfCodes.drawQr(content, contact, ErrorCorrectionLevel.Q, box.left(), y,
        Measures.mm(28), NebulaColors.BLUE);

The corporate blue is dark (#1F3A5F) and has enough contrast on white: it scans without any problems. Try it with NebulaColors.ORANGE: ZXing still reads it thanks to its adaptive binarizer, but the contrast is much lower and, with simpler readers, low toner or poor lighting, the safety margin disappears. For documents that get printed, dark on white. Thanks to the UTF-8 CHARACTER_SET, any accented characters in the contact details (such as the "é" in a Spanish name) appear correctly in the phone's contacts.

Conclusion

PDFBox draws and ZXing encodes: with that division of labour you can now add any code to your documents. You know that ZXing returns a BitMatrix of modules, that the quiet zone and the X dimension decide whether a code scans, that the QR correction level changes its size (L, M, Q, H), that Code 128 is the right linear code for delivery note numbers and that drawing the modules as vector rectangles gives maximum sharpness with very little weight. PdfCodes sums it all up, and CheckCodes lets you automatically verify that the codes scan. You also know that a QR code with tax validity must follow the official specifications, which should be reviewed with a professional.

You now have all the pieces of a business document: header, multipage tables, numbered footers and codes. But they're spread across example classes with a lot of repeated code (creating the document, the fonts, the paginator, numbering, saving...). In the next lesson you'll design the architecture of a reusable document generator: separating the model from the layout, a shared context, composable blocks and a centralised style theme, and you'll put it to the test by generating a delivery note.

PDF Generation and Editing with Apache PDFBox

Module 1: PDF and PDFBox Fundamentals

Module 2: Generating Content

Module 3: Business Documents

Module 4: Editing Existing PDFs

Module 5: AcroForm Forms

Module 6: Extraction and Analysis

Module 7: Security and Digital Signatures

Module 8: PDFBox in Production

© Copyright 2026. All rights reserved