In module 1 we placed the text "Hello, InvoiceLab" at position (72, 770) more or less by eye. To generate a real invoice we need the opposite: to know exactly where every element lands. In this lesson you'll learn which unit a PDF page is measured in (the point), how to convert millimetres to points, where the coordinate origin is (and why it isn't where you'd expect), how page sizes are defined with PDRectangle, what the five "boxes" of a page are, how rotation affects things, and how coordinates are transformed with the transformation matrix (CTM). We'll finish with three utilities InvoiceLab will use throughout the course: Measures, ContentBox and ReferenceGrid, a 1 cm grid that will act as your "graph paper" for layout work.

Contents

  1. The unit of measurement: the point
  2. Converting millimetres to points: the Measures class
  3. The coordinate origin: bottom left
  4. Page sizes with PDRectangle
  5. The boxes of a page: MediaBox, CropBox, BleedBox, TrimBox and ArtBox
  6. Page rotation (/Rotate)
  7. Margins and the invoice content box: the ContentBox class
  8. The transformation matrix (CTM) and the Matrix class
  9. Saving and restoring the graphics state
  10. Flipping the Y axis: use a function, not the matrix
  11. A 1 cm reference grid

The unit of measurement: the point

Every coordinate and dimension in a PDF is expressed in points (abbreviated pt). A PDF point is exactly 1/72 of an inch:

Unit Equivalent in points
1 inch (25.4 mm) 72 pt
1 centimetre ≈ 28.35 pt
1 millimetre ≈ 2.835 pt
1 point ≈ 0.353 mm

Some practical consequences:

  • A PDF has no pixels and no resolution: coordinates are real numbers (float) and you can use decimals such as 56.69. Resolution only comes into play when the PDF is printed or rendered on screen.
  • Font size is also measured in points: 12 pt text is the same "12" you use in a word processor.
  • An A4 page (210 × 297 mm) measures 595.28 × 841.89 pt. Remember the approximate figure 595 × 842: you'll see it all the time.

PDF lets you change the user unit with the page's /UserUnit entry, but almost no software uses it. In this course we'll always work in points.

Converting millimetres to points: the Measures class

In Spain, document designs are thought out in millimetres: "a 2 cm margin", "a logo 40 mm wide". Writing 56.69f in the code instead of "20 mm" makes the code unreadable, so we'll create a small utility class in the com.invoicelab.pdf package, which from now on will hold the reusable building blocks for generating documents:

package com.invoicelab.pdf;

/**
 * Conversions between real-world units and PDF points (1 pt = 1/72 inch).
 */
public final class Measures {

    public static final float POINTS_PER_INCH = 72f;
    public static final float MM_PER_INCH = 25.4f;

    private Measures() {
        // utility class: not meant to be instantiated
    }

    /** Converts millimetres to PDF points. */
    public static float mm(double millimetres) {
        return (float) (millimetres * POINTS_PER_INCH / MM_PER_INCH);
    }

    /** Converts centimetres to PDF points. */
    public static float cm(double centimetres) {
        return mm(centimetres * 10);
    }

    /** Converts inches to PDF points. */
    public static float inches(double inches) {
        return (float) (inches * POINTS_PER_INCH);
    }

    /** Converts PDF points to millimetres (handy for debugging and displaying measurements). */
    public static float toMm(double points) {
        return (float) (points * MM_PER_INCH / POINTS_PER_INCH);
    }
}

Details worth noting:

  • final and a private constructor: this is a utility class with static methods; nobody should create instances of it or extend it.
  • double parameters, float result: accepting double lets you write Measures.mm(20) or Measures.mm(12.5) without suffixes; the result is a float because PDFBox's entire drawing API uses float.
  • The formula is a simple proportion: mm × 72 / 25.4. For example, Measures.mm(20) returns 56.69.
  • toMm does the reverse conversion; we'll use it to print readable measurements while debugging.

If you add import static com.invoicelab.pdf.Measures.mm;, the code becomes even more compact: content.newLineAtOffset(mm(18), mm(250));.

The coordinate origin: bottom left

Here's the first surprise for anyone coming from Swing, HTML or graphic design: in a PDF the origin (0, 0) is at the bottom-left corner of the page, the X axis grows to the right and the Y axis grows upwards, just like in school maths.

flowchart TB
    subgraph Page["A4 page (595 x 842 pt)"]
        direction TB
        TL["(0, 842)<br/>top-left corner"] ~~~ TR["(595, 842)<br/>top-right corner"]
        BL["(0, 0)<br/>ORIGIN: bottom-left corner"] ~~~ BR["(595, 0)<br/>bottom-right corner"]
    end
I want to place something… Y coordinate on an A4 page
Flush with the bottom edge y = 0
2 cm from the bottom edge y = Measures.cm(2) ≈ 56.7
Vertically centred y = 842 / 2 = 421
2 cm from the top edge y = 842 - Measures.cm(2) ≈ 785.2
Flush with the top edge y = 842

That's why in HelloInvoiceLab we used y = 770: it's "near the top" (842 − 770 = 72 pt = 1 inch from the top edge). Later in this lesson we'll see how to avoid these mental subtractions.

Page sizes with PDRectangle

The org.apache.pdfbox.pdmodel.common.PDRectangle class represents a rectangle with its lower-left corner (lowerLeftX, lowerLeftY) and its upper-right corner (upperRightX, upperRightY). It's used to define the size of pages (and, as we'll see, their boxes).

Predefined constants

Constant Size (mm) Size (pt) Typical use
PDRectangle.A0 … A6 A4 = 210 × 297 A4 = 595.28 × 841.89 Europe: A4 for invoices, A5 for small delivery notes
PDRectangle.A5 148 × 210 419.53 × 595.28 Delivery notes, vouchers
PDRectangle.A3 297 × 420 841.89 × 1190.55 Plans, posters
PDRectangle.LETTER 215.9 × 279.4 612 × 792 USA (it's the default size for new PDPage())
PDRectangle.LEGAL 215.9 × 355.6 612 × 1008 Legal documents in the USA

Custom and landscape sizes

There are two very useful constructors:

  • new PDRectangle(width, height): a rectangle with its origin at (0, 0).
  • new PDRectangle(x, y, width, height): a rectangle with its origin at (x, y).

There's no "A4 landscape" constant: all you have to do is swap width and height. The following example creates a PDF with five pages of different sizes, including an 80 mm receipt like the ones printed by thermal printers:

package com.invoicelab.examples;

import com.invoicelab.pdf.Measures;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;

public class PageSizes {

    public static void main(String[] args) throws IOException {
        Files.createDirectories(Path.of("output"));

        PDRectangle a4Landscape = new PDRectangle(PDRectangle.A4.getHeight(), PDRectangle.A4.getWidth());
        PDRectangle receipt = new PDRectangle(Measures.mm(80), Measures.mm(200));   // 80 mm receipt

        PDRectangle[] sizes = { PDRectangle.A4, PDRectangle.A5, PDRectangle.LETTER, a4Landscape, receipt };
        String[] names = { "A4", "A5", "LETTER", "A4 landscape", "Receipt 80 mm" };

        try (PDDocument document = new PDDocument()) {
            for (int i = 0; i < sizes.length; i++) {
                PDRectangle r = sizes[i];
                document.addPage(new PDPage(r));
                System.out.printf("%-13s %7.2f x %7.2f pt  =  %6.1f x %6.1f mm%n",
                        names[i], r.getWidth(), r.getHeight(),
                        Measures.toMm(r.getWidth()), Measures.toMm(r.getHeight()));
            }
            document.save("output/page-sizes.pdf");
        }
    }
}

Console output (with an English locale, which uses a decimal point):

A4             595.28 x  841.89 pt  =   210.0 x  297.0 mm
A5             419.53 x  595.28 pt  =   148.0 x  210.0 mm
LETTER         612.00 x  792.00 pt  =   215.9 x  279.4 mm
A4 landscape   841.89 x  595.28 pt  =   297.0 x  210.0 mm
Receipt 80 mm  226.77 x  566.93 pt  =    80.0 x  200.0 mm

Notice that each page of a PDF can have its own size: there's no such thing as a "document size", only a size per page. Also, PDRectangle is mutable; never modify the shared constants (PDRectangle.A4.setUpperRightX(...) would change A4 for your entire application). If you need a variation, create a new one.

The boxes of a page: MediaBox, CropBox, BleedBox, TrimBox and ArtBox

A PDF page can declare up to five rectangles. For office documents such as an invoice only the first one matters, but it's worth knowing all of them because they show up in PDFs you'll receive from print shops or other software.

Box Required Meaning If not defined
MediaBox Yes Size of the physical "paper": the full area of the page —
CropBox No Region visible on screen and when printing in the office = MediaBox
BleedBox No Area including bleed for professional printing (the background extends a few mm beyond the cut) = CropBox
TrimBox No Final size of the page after it's cut with the guillotine = CropBox
ArtBox No Area with "meaningful" content (for placing the page inside another design) = CropBox
flowchart LR
    M["MediaBox<br/>full paper"] --> B["BleedBox<br/>cut + bleed"] --> T["TrimBox<br/>final size"] --> A["ArtBox<br/>meaningful content"]

new PDPage(PDRectangle.A4) only defines the MediaBox. PDFBox's getters already apply the defaults from the table: getCropBox() returns the MediaBox if there's no CropBox, and so on.

Let's look at a print-shop case: an A4 leaflet with 3 mm of bleed. The paper must be 6 mm wider and taller, and the final cut is the centred A4:

package com.invoicelab.examples;

import com.invoicelab.pdf.Measures;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;

public class PageBoxes {

    public static void main(String[] args) throws IOException {
        float bleed = Measures.mm(3);
        PDRectangle a4 = PDRectangle.A4;
        PDRectangle paper = new PDRectangle(a4.getWidth() + 2 * bleed, a4.getHeight() + 2 * bleed);
        PDRectangle trim = new PDRectangle(bleed, bleed, a4.getWidth(), a4.getHeight());

        try (PDDocument document = new PDDocument()) {
            PDPage page = new PDPage(paper);   // MediaBox = full paper
            page.setBleedBox(paper);           // how far the printed background extends
            page.setTrimBox(trim);             // final size after the guillotine (A4)
            page.setCropBox(trim);             // what the viewer shows on screen
            document.addPage(page);
            document.save("output/page-boxes.pdf");
        }

        try (PDDocument document = Loader.loadPDF(new File("output/page-boxes.pdf"))) {
            PDPage p = document.getPage(0);
            print("MediaBox", p.getMediaBox());
            print("CropBox ", p.getCropBox());
            print("BleedBox", p.getBleedBox());
            print("TrimBox ", p.getTrimBox());
            print("ArtBox  ", p.getArtBox());
        }
    }

    private static void print(String name, PDRectangle r) {
        System.out.printf("%s [%.1f %.1f %.1f %.1f]  (%.1f x %.1f mm)%n", name,
                r.getLowerLeftX(), r.getLowerLeftY(), r.getUpperRightX(), r.getUpperRightY(),
                Measures.toMm(r.getWidth()), Measures.toMm(r.getHeight()));
    }
}
MediaBox [0.0 0.0 612.3 858.9]  (216.0 x 303.0 mm)
CropBox  [8.5 8.5 603.8 850.4]  (210.0 x 297.0 mm)
BleedBox [0.0 0.0 612.3 858.9]  (216.0 x 303.0 mm)
TrimBox  [8.5 8.5 603.8 850.4]  (210.0 x 297.0 mm)
ArtBox   [8.5 8.5 603.8 850.4]  (210.0 x 297.0 mm)

Note two things:

  • The CropBox starts at (8.5, 8.5), not at (0, 0). Drawing coordinates always refer to the MediaBox: if you want to draw in the visible corner, you'll have to add the CropBox origin. That's why our utilities will use getLowerLeftX()/getLowerLeftY() instead of assuming zero.
  • getArtBox() returns the CropBox because we didn't define one: that's the default value.

Rule for InvoiceLab: our invoices only define the MediaBox (A4). The other boxes will matter when you process third-party PDFs (module 4) or prepare documents for professional printing.

Page rotation (/Rotate)

A page can carry the /Rotate entry with a value that's a multiple of 90 (0, 90, 180, 270). It tells viewers to display the page rotated by that number of degrees clockwise. What matters is what it does not do: it doesn't change the MediaBox or the coordinate system of the content.

PDPage page = new PDPage(PDRectangle.A4);
page.setRotation(90);      // writes /Rotate 90 into the page dictionary
System.out.println(page.getRotation());    // 90
System.out.println(page.getMediaBox());    // [0.0,0.0,595.27563,841.8898]  still portrait!

If you draw text at (50, 780) on a page with /Rotate 90, the viewer shows the page in landscape, but your text appears vertically, running along the right edge, because it was placed in the unrotated coordinate system.

I want to… Best option
Create a new landscape document new PDPage(new PDRectangle(height, width)): no /Rotate, no surprises
Rotate an existing page (for example, a crooked scan) setRotation(...) (module 4, manipulating pages)
Add content to a page that already has /Rotate Compensate for the rotation with a transformation (see below)

To write horizontally on a page with /Rotate 90, you apply a transformation that "undoes" the rotation. We haven't covered matrices yet; come back to this example after reading the CTM section:

PDPage page = new PDPage(PDRectangle.A4);   // portrait MediaBox: 595 x 842
page.setRotation(90);                        // displayed in landscape
document.addPage(page);

float mediaBoxWidth = page.getMediaBox().getWidth();
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
    // From here on, (0,0) is the bottom-left corner of the page
    // AS IT IS DISPLAYED, which is 842 pt wide and 595 pt tall.
    content.transform(new Matrix(0, 1, -1, 0, mediaBoxWidth, 0));
    content.beginText();
    content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 14);
    content.newLineAtOffset(50, 540);
    content.showText("Horizontal text on a page with /Rotate 90");
    content.endText();
}

Margins and the invoice content box: the ContentBox class

A professional document never draws right up to the edge: office printers can't print the last few millimetres of the paper, and text pressed against the edge is uncomfortable to read. Let's set the margins for Nebula Distribution's invoices:

Margin Value In points
Top 20 mm 56.69
Bottom 20 mm 56.69
Left 18 mm 51.02
Right 18 mm 51.02

What's left inside is the content box: 174 × 257 mm on an A4 page. All the invoice content (header, details, table, totals) will live inside it. We represent it with a Java 17 record, which gives us a constructor, getters, equals and toString without writing them:

package com.invoicelab.pdf;

import org.apache.pdfbox.pdmodel.common.PDRectangle;

/**
 * Area of the page where drawing is allowed: the page minus its margins.
 * All coordinates are in points and in the PDF system (origin bottom-left).
 */
public record ContentBox(float left, float bottom, float right, float top) {

    /** Creates the content box of a page from its margins (in points). */
    public static ContentBox of(PDRectangle page, float topMargin, float rightMargin,
                                float bottomMargin, float leftMargin) {
        return new ContentBox(
                page.getLowerLeftX() + leftMargin,
                page.getLowerLeftY() + bottomMargin,
                page.getUpperRightX() - rightMargin,
                page.getUpperRightY() - topMargin);
    }

    /** Standard content box for InvoiceLab invoices: 20 mm top/bottom, 18 mm on the sides. */
    public static ContentBox invoice(PDRectangle page) {
        return of(page, Measures.mm(20), Measures.mm(18), Measures.mm(20), Measures.mm(18));
    }

    public float width() {
        return right - left;
    }

    public float height() {
        return top - bottom;
    }

    /**
     * Translates a distance measured from the TOP edge of the box
     * (the way a design is thought out) into the PDF Y coordinate.
     */
    public float yFromTop(float distance) {
        return top - distance;
    }

    /** Does an element of this height fit if its top edge is at y? */
    public boolean fits(float y, float height) {
        return y - height >= bottom;
    }

    public PDRectangle asRectangle() {
        return new PDRectangle(left, bottom, width(), height());
    }
}

What each part does:

  • The four components (left, bottom, right, top) are the edges of the box in PDF coordinates. Storing edges instead of "x, y, width, height" simplifies the most common calculations (right-aligning uses right(), starting at the top uses top()).
  • of(...) follows the CSS order for margins (top, right, bottom, left) and respects the origin of the page rectangle, in case it isn't (0, 0).
  • invoice(...) centralizes the corporate margins: if they change tomorrow, you only touch them in one place.
  • yFromTop(...) is our function for "flipping the Y axis"; we explain it in detail below.
  • fits(...) will be essential in module 3 for deciding when to break to a new page.

The transformation matrix (CTM) and the Matrix class

Everything you draw in a PDF goes through the current transformation matrix (CTM). This matrix converts the coordinates you write (user space) into page coordinates. When a content stream begins, the CTM is the identity: what you write is what you get.

A PDF matrix has six numbers [a b c d e f] and transforms a point (x, y) like this:

x' = a·x + c·y + e
y' = b·x + d·y + f
Transformation Matrix [a b c d e f] PDFBox method
Identity [1 0 0 1 0 0] new Matrix()
Translation by (tx, ty) [1 0 0 1 tx ty] Matrix.getTranslateInstance(tx, ty)
Scaling (sx, sy) [sx 0 0 sy 0 0] Matrix.getScaleInstance(sx, sy)
Rotation by θ (counter-clockwise) [cos θ sin θ −sin θ cos θ 0 0] Matrix.getRotateInstance(θ, tx, ty) (θ in radians; it rotates and also translates to (tx, ty))

To modify the CTM you call content.transform(matrix), which writes the cm operator into the content stream. Each call accumulates on top of the previous one: it's like moving and rotating the sheet of paper before carrying on drawing.

This is the most powerful idea in the section: you always draw the same way, at (0, 0), and the CTM decides where the drawing ends up. The following example draws the same "stamp" (a rectangle with text) four times, applying different transformations:

package com.invoicelab.examples;

import com.invoicelab.pdf.Measures;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.apache.pdfbox.util.Matrix;

public class CtmTransformations {

    public static void main(String[] args) throws IOException {
        PDType1Font helvetica = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
        try (PDDocument document = new PDDocument()) {
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);
            try (PDPageContentStream content = new PDPageContentStream(document, page)) {

                // 1) Untransformed: the stamp appears in the bottom-left corner
                drawStamp(content, helvetica, "original");

                // 2) Translated 3 cm to the right and 25 cm up
                content.saveGraphicsState();
                content.transform(Matrix.getTranslateInstance(Measures.cm(3), Measures.cm(25)));
                drawStamp(content, helvetica, "translated");
                content.restoreGraphicsState();

                // 3) Translated and then scaled to double size
                content.saveGraphicsState();
                content.transform(Matrix.getTranslateInstance(Measures.cm(3), Measures.cm(18)));
                content.transform(Matrix.getScaleInstance(2, 2));
                drawStamp(content, helvetica, "scaled x2");
                content.restoreGraphicsState();

                // 4) Rotated 30 degrees (counter-clockwise) with its origin at (12 cm, 8 cm)
                content.saveGraphicsState();
                content.transform(Matrix.getRotateInstance(Math.toRadians(30), Measures.cm(12), Measures.cm(8)));
                drawStamp(content, helvetica, "rotated 30°");
                content.restoreGraphicsState();
            }
            document.save("output/ctm-transformations.pdf");
        }
    }

    /** Always draws at (0,0): the CTM decides where it ends up on the page. */
    private static void drawStamp(PDPageContentStream content, PDType1Font font, String text)
            throws IOException {
        content.addRect(0, 0, Measures.cm(4), Measures.cm(1.5));   // 4 x 1.5 cm rectangle
        content.stroke();                                           // stroke its outline
        content.beginText();
        content.setFont(font, 10);
        content.newLineAtOffset(Measures.mm(3), Measures.mm(6));
        content.showText(text);
        content.endText();
    }
}

Key points:

  • addRect + stroke draw the outline of a rectangle; vector graphics are covered in depth in lesson 02-05.
  • In case 3, the translation is applied first and the scaling afterwards: the scaling acts in the already translated system, so the stamp grows from its own corner, not from the page origin. If you reverse the order, the translation would also be multiplied by 2 and the stamp would end up at 6 cm and 36 cm (off the page!).
  • Math.toRadians(30): PDFBox expects radians. A positive angle rotates counter-clockwise (because the Y axis points up).
  • Scaling affects everything: the line width and the text size are doubled too.

In the content stream (uncompressed, as you learned in 01-05) you'll see this for case 2. Every number is in points: 85.03937 is 3 cm and 708.66144 is 25 cm:

q
1 0 0 1 85.03937 708.66144 cm
0 0 113.38583 42.51968 re
S
BT
/F1 10 Tf
8.50394 17.00787 Td
(translated) Tj
ET
Q

Saving and restoring the graphics state

In the previous example each transformation sits between saveGraphicsState() and restoreGraphicsState(), which generate the q and Q operators. The graphics state includes, among other things:

  • The CTM.
  • The stroke and fill colours.
  • The line width and line style.
  • The clipping region.

q saves a copy of the state onto a stack; Q restores the last saved copy. Without them, the second stamp would be translated on top of the first one's translation and everything would end up out of place.

sequenceDiagram
    participant C as Code
    participant P as State stack
    C->>P: saveGraphicsState() → q (saves identity CTM)
    C->>C: transform(translation) → cm
    C->>C: draw stamp
    C->>P: restoreGraphicsState() → Q (restores the identity)
    Note over C: the next drawing starts from the origin again

Rules:

  • Every q must have its matching Q within the same content stream. PDFBox doesn't check this for you.
  • Pairs can be nested (q q Q Q), like parentheses.
  • You can't use q/Q inside a text block (beginText/endText): save the state first and then open the text.
  • Make it a habit: any helper method that changes the graphics state must save it at the start and restore it at the end, so it doesn't "contaminate" the calling code.

Flipping the Y axis: use a function, not the matrix

We think about designs from the top down: "the logo goes 10 mm from the top edge; the invoice number, 15 mm further down". In a PDF you have to subtract from the page height. There are two ways to deal with this.

Tempting option (not recommended): flip the CTM

With the matrix [1 0 0 -1 0 height] the Y axis starts growing downwards:

content.transform(new Matrix(1, 0, 0, -1, 0, page.getMediaBox().getHeight()));

It works for coordinates, but it flips everything: text comes out upside down and mirrored, so do images, and you'd have to compensate for every element with another flip. It's a constant source of bugs.

Recommended option: a helper function

We keep the PDF coordinate system and translate distances with a function, which is exactly what ContentBox.yFromTop does:

ContentBox box = ContentBox.invoice(page.getMediaBox());
float yTitle = box.yFromTop(Measures.mm(15));   // 15 mm below the top margin
  • The design is expressed in natural terms ("15 mm from the top").
  • Text, images and graphics are drawn without odd transformations.
  • If the margins change, every position is recalculated automatically.

For the rest of the course we'll calculate vertical positions this way: starting from box.top() and subtracting as we move down the page.

A 1 cm reference grid

While you're laying out a page, it's very useful to see a grid over it to check that an element really is "2 cm from the edge". We'll create ReferenceGrid, which draws a line every centimetre (darker every 5 cm) and labels the axes:

package com.invoicelab.pdf;

import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;

/**
 * Draws a 1 cm grid over a page as a layout aid.
 * For development only: never in documents delivered to customers.
 */
public final class ReferenceGrid {

    private ReferenceGrid() {
    }

    public static void draw(PDPageContentStream content, PDRectangle page) throws IOException {
        float step = Measures.cm(1);
        float width = page.getWidth();
        float height = page.getHeight();

        content.saveGraphicsState();
        content.setLineWidth(0.25f);

        // Vertical lines
        int column = 0;
        for (float x = 0; x <= width; x += step, column++) {
            content.setStrokingColor(column % 5 == 0 ? 0.55f : 0.85f); // darker every 5 cm
            content.moveTo(x, 0);
            content.lineTo(x, height);
            content.stroke();
        }
        // Horizontal lines
        int row = 0;
        for (float y = 0; y <= height; y += step, row++) {
            content.setStrokingColor(row % 5 == 0 ? 0.55f : 0.85f);
            content.moveTo(0, y);
            content.lineTo(width, y);
            content.stroke();
        }

        // Labels in centimetres along the bottom and left axes
        PDType1Font font = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
        content.setNonStrokingColor(0.4f);
        for (int cm = 0; cm * step < width; cm++) {
            label(content, font, cm * step + 1, 2, String.valueOf(cm));
        }
        for (int cm = 1; cm * step < height; cm++) {
            label(content, font, 2, cm * step + 1, String.valueOf(cm));
        }
        content.restoreGraphicsState();
    }

    private static void label(PDPageContentStream content, PDType1Font font,
                              float x, float y, String text) throws IOException {
        content.beginText();
        content.setFont(font, 6);
        content.newLineAtOffset(x, y);
        content.showText(text);
        content.endText();
    }
}

How it works:

  • moveTo(x, y) positions the "pen" without drawing, lineTo(x, y) adds a segment and stroke() draws it. It's a minimal preview of lesson 02-05.
  • setStrokingColor(0.85f) with a single float is a grey (0 = black, 1 = white). The lines every 5 cm are darker (0.55f), as on graph paper.
  • setLineWidth(0.25f): very thin lines so they don't obscure the content.
  • The method follows the rule from the previous section: saveGraphicsState() at the start and restoreGraphicsState() at the end, so the colour and line width don't affect whatever is drawn afterwards.
  • The labels are written in a 6 pt standard font; the details of text come in lesson 02-02.

Now an example that brings it all together: the grid, the content box outlined in red, and a piece of text placed "15 mm from the top margin":

package com.invoicelab.examples;

import com.invoicelab.pdf.ContentBox;
import com.invoicelab.pdf.Measures;
import com.invoicelab.pdf.ReferenceGrid;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;

public class LayoutTemplate {

    public static void main(String[] args) throws IOException {
        Files.createDirectories(Path.of("output"));
        PDType1Font helvetica = new PDType1Font(Standard14Fonts.FontName.HELVETICA);

        try (PDDocument document = new PDDocument()) {
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);
            ContentBox box = ContentBox.invoice(page.getMediaBox());

            try (PDPageContentStream content = new PDPageContentStream(document, page)) {
                ReferenceGrid.draw(content, page.getMediaBox());

                // Red outline of the content box
                content.setStrokingColor(1f, 0f, 0f);
                content.setLineWidth(0.75f);
                content.addRect(box.left(), box.bottom(), box.width(), box.height());
                content.stroke();

                // Text placed "15 mm from the top edge of the content box"
                content.setNonStrokingColor(0f);
                content.beginText();
                content.setFont(helvetica, 12);
                content.newLineAtOffset(box.left(), box.yFromTop(Measures.mm(15)));
                content.showText("Invoice F-2026-0001");
                content.endText();
            }
            document.save("output/layout-template.pdf");
            System.out.printf("Content box: %.1f x %.1f mm%n", Measures.toMm(box.width()), Measures.toMm(box.height()));
        }
    }
}

Open output/layout-template.pdf and use the grid to check that the red rectangle starts at 1.8 cm horizontally and 2 cm vertically, and that the console prints Content box: 174.0 x 257.0 mm. A practical tip: while developing the invoice you can enable the grid with a system property (-Dinvoicelab.grid=true) and disable it in production.

Common Mistakes and Tips

  • Thinking in pixels or with Y pointing down. The origin is at the bottom left and Y grows upwards. If an element "disappears", check that its Y isn't negative or greater than the page height.
  • Using new PDPage() with no arguments. It creates a Letter page (612 × 792). In InvoiceLab, always use new PDPage(PDRectangle.A4).
  • Modifying PDRectangle.A4. It's a shared but mutable constant; always create new rectangles.
  • Assuming the page starts at (0, 0). In third-party PDFs the MediaBox or CropBox may have a non-zero origin; use getLowerLeftX()/getLowerLeftY().
  • Using /Rotate to create landscape documents. It works, but it forces you to compensate for the rotation in every drawing. Swap width and height in the PDRectangle instead.
  • Forgetting restoreGraphicsState(). Transformations and colours "leak" into the rest of the page. Always pair q and Q.
  • Passing degrees to getRotateInstance. It expects radians: Math.toRadians(degrees).
  • Leaving the grid in production. It's a layout tool; enable it only during development.

Exercises

  1. A6 shipping labels. Create a PDF with a landscape A6 page (148 × 105 mm) for Nebula Distribution's parcel labels. Use a ContentBox with 5 mm margins on all four sides, draw its outline and write "RECIPIENT" 8 mm from the top edge of the box. Print the size of the content box in millimetres to the console.
  2. Content box corners. Write a method markCorners(PDPageContentStream content, ContentBox box) that uses transform and a single method that draws a small 5 mm "L" at (0, 0) to draw a mark at each of the four corners of the content box, pointing inwards (hint: translation + rotation by 0, 90, 180 and 270 degrees).
  3. Reverse conversion. Without running any code: how far (in mm) from the top edge of an A4 page is text placed at y = 770? And text placed at box.yFromTop(Measures.mm(15)) using the invoice box?

Solutions

Solution 1.

PDRectangle a6Landscape = new PDRectangle(PDRectangle.A6.getHeight(), PDRectangle.A6.getWidth());
try (PDDocument document = new PDDocument()) {
    PDPage page = new PDPage(a6Landscape);
    document.addPage(page);
    float m = Measures.mm(5);
    ContentBox box = ContentBox.of(page.getMediaBox(), m, m, m, m);

    try (PDPageContentStream content = new PDPageContentStream(document, page)) {
        content.addRect(box.left(), box.bottom(), box.width(), box.height());
        content.stroke();
        content.beginText();
        content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD), 12);
        content.newLineAtOffset(box.left() + Measures.mm(3), box.yFromTop(Measures.mm(8)));
        content.showText("RECIPIENT");
        content.endText();
    }
    document.save("output/label-a6.pdf");
    System.out.printf("Content box: %.1f x %.1f mm%n", Measures.toMm(box.width()), Measures.toMm(box.height()));
}

The console shows Content box: 138.0 x 95.0 mm. Notice that landscape A6 is obtained by swapping width and height, just as we did with A4.

Solution 2.

static void markCorners(PDPageContentStream content, ContentBox box) throws IOException {
    float[][] corners = {
            { box.left(), box.bottom(), 0 },     // bottom left: no rotation
            { box.right(), box.bottom(), 90 },   // bottom right
            { box.right(), box.top(), 180 },     // top right
            { box.left(), box.top(), 270 } };    // top left
    for (float[] c : corners) {
        content.saveGraphicsState();
        content.transform(Matrix.getRotateInstance(Math.toRadians(c[2]), c[0], c[1]));
        drawL(content);
        content.restoreGraphicsState();
    }
}

/** A 5 mm "L" with its vertex at (0,0), opening upwards and to the right. */
static void drawL(PDPageContentStream content) throws IOException {
    content.moveTo(0, Measures.mm(5));
    content.lineTo(0, 0);
    content.lineTo(Measures.mm(5), 0);
    content.stroke();
}

When rotated 90° counter-clockwise, the "L" that opened to the right and upwards now opens upwards and to the left: exactly what the bottom-right corner needs. This is the central idea of the CTM: a single drawing method, and the matrix takes care of positioning and orienting it. The save/restore pair stops the rotations from accumulating.

Solution 3.

  • y = 770: the distance to the top edge is 841.89 − 770 = 71.89 pt, that is, 71.89 × 25.4 / 72 ≈ 25.4 mm (one inch).
  • box.yFromTop(Measures.mm(15)): the top margin is 20 mm, so the text sits 20 + 15 = 35 mm from the top edge. Careful: that coordinate is the text's baseline (the line the letters "sit" on); the tops of the letters are a few millimetres higher. We'll study this in lessons 02-02 and 02-04.

Conclusion

You now know how to measure and find your way around a PDF page: you work in points (1/72 of an inch) and convert from millimetres with Measures.mm(...), you know the origin is at the bottom left, you define sizes with PDRectangle (including landscape and custom ones), you can tell the five boxes of a page apart, and you know why /Rotate doesn't change the coordinate system. You've learned to use the CTM with Matrix to translate, scale and rotate, always protected by saveGraphicsState/restoreGraphicsState, and you've created InvoiceLab's first building blocks: Measures, ContentBox (with its yFromTop) and ReferenceGrid.

With the "graph paper" ready, it's time to write on it. In the next lesson we'll take an in-depth look at PDPageContentStream and the text operators (BT/ET, Tf, Td, Tm, TL, Tj/TJ), the 14 standard fonts and their styles, and we'll write the issuer and customer data blocks of the invoice.

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