An invoice isn't just text. The lines that separate sections, the box that highlights the totals or the corporate colour band in the header are the elements that make a document look professional and easy to read at a glance. In PDF all of them are vector graphics: shapes described with coordinates and operators, not pixels, so they look sharp at any zoom level and take up hardly any space. In this lesson you'll learn to build paths with moveTo, lineTo and curveTo, to draw rectangles, to stroke and fill them, to control line width and style, to use RGB, CMYK and grey colours, to apply transparency and to restrict drawing with a clipping region. With all of this we'll create the NebulaColors palette and the Shapes utility, and draw the invoice's corporate band, separator lines and totals box.
Contents
- How drawing works in PDF: build a path and paint it
- Building paths:
moveTo,lineTo,curveTo,closePathandaddRect - Painting the path:
stroke,fillandfillAndStroke - Line style: width, dashes, caps and joins
- Colour: RGB, CMYK and greyscale
- The
NebulaColorscorporate palette - Transparency with
PDExtendedGraphicsState - Rounded rectangles with Bézier curves
- Clipping
- The
Shapesutility - InvoiceLab example: corporate band, separators and totals box
How drawing works in PDF: build a path and paint it
Drawing in PDF always happens in two phases:
- Build a path: a sequence of straight and curved segments that is still invisible, like a pencil sketch.
- Paint the path: stroke its outline, fill its interior, both, or use it as a clipping region. Painting consumes the path, and the next one starts from scratch.
flowchart LR
A["moveTo / lineTo / curveTo<br/>closePath / addRect"] -->|build| R["Current path<br/>(invisible)"]
R -->|stroke| S["Outline"]
R -->|fill| F["Fill"]
R -->|fillAndStroke| FS["Fill + outline"]
R -->|clip| C["Clipping region"]
The final look depends on the graphics state at the moment of painting: stroke and fill colours, line width and style, transparency and CTM. Remember from lesson 02-01 that this state is saved and restored with saveGraphicsState()/restoreGraphicsState() (q/Q).
As with text, all of this happens outside text objects: calling moveTo or addRect between beginText() and endText() throws IllegalStateException: Error: moveTo is not allowed within a text block.
Building paths: moveTo, lineTo, curveTo, closePath and addRect
| Method | Operator | What it does |
|---|---|---|
moveTo(x, y) |
m |
Starts a new subpath at (x, y) without drawing (lifts the pen) |
lineTo(x, y) |
l |
Adds a straight segment from the current point to (x, y) |
curveTo(x1, y1, x2, y2, x3, y3) |
c |
Adds a cubic Bézier curve to (x3, y3) with two control points |
closePath() |
h |
Closes the subpath with a straight segment back to its starting point |
addRect(x, y, width, height) |
re |
Adds a complete (closed) rectangle with its lower-left corner at (x, y) |
A cubic Bézier curve runs from the current point to the end point (x3, y3) and is "pulled" by two control points: (x1, y1) sets the direction in which the curve leaves, and (x2, y2) the direction from which it arrives. The curve doesn't pass through the control points. It's the same "pen" tool found in design software.
// 1) Simple line
content.moveTo(Measures.cm(2), y);
content.lineTo(Measures.cm(8), y);
content.stroke();
// 2) Triangle: closed path, outline only
content.moveTo(Measures.cm(10), y - Measures.cm(2));
content.lineTo(Measures.cm(13), y - Measures.cm(2));
content.lineTo(Measures.cm(11.5f), y + Measures.cm(0.5f));
content.closePath(); // back to the first vertex
content.stroke();
// 3) Bézier curve (a "wave")
content.moveTo(Measures.cm(2), y);
content.curveTo(Measures.cm(5), y + Measures.cm(2), // control point 1: pulls upwards
Measures.cm(8), y - Measures.cm(2), // control point 2: pulls downwards
Measures.cm(11), y); // end point
content.stroke();Why closePath() and not a final lineTo back to the starting vertex? Visually they look the same, but with closePath the viewer knows the shape is closed and joins the last corner properly (with whichever join style you choose); with lineTo you'd get two overlapping line ends and, with thick lines, a visible notch.
Painting the path: stroke, fill and fillAndStroke
| Method | Operator | Colour used | Result |
|---|---|---|---|
stroke() |
S |
Stroke (setStrokingColor) |
Outline only |
closeAndStroke() |
s |
Stroke | Closes the path and strokes the outline |
fill() |
f |
Fill (setNonStrokingColor) |
Interior only |
fillAndStroke() |
B |
Both | Interior and outline |
fillEvenOdd() |
f* |
Fill | Interior according to the even-odd rule (holes in self-intersecting shapes) |
content.setNonStrokingColor(new Color(0xE8, 0xEE, 0xF5)); // fill: very light blue
content.setStrokingColor(new Color(0x1F, 0x3A, 0x5F)); // stroke: corporate blue
content.setLineWidth(2);
content.addRect(Measures.cm(2), y, Measures.cm(4), Measures.cm(2));
content.fill(); // light blue rectangle with no border
content.addRect(Measures.cm(7.5f), y, Measures.cm(4), Measures.cm(2));
content.stroke(); // blue border only
content.addRect(Measures.cm(13), y, Measures.cm(4), Measures.cm(2));
content.fillAndStroke(); // fill and borderTwo details worth knowing:
- The stroke is centred on the path: with a 2 pt line, 1 pt falls outside the rectangle and 1 pt inside. Bear this in mind if you need a bordered box to take up an exact size.
- Order matters: whatever is painted later covers what came before. Backgrounds first, then borders and text.
Line style: width, dashes, caps and joins
| Method | Operator | Values |
|---|---|---|
setLineWidth(float) |
w |
Width in points. 0 means "the thinnest line the device can draw" (avoid it: on a professional press it's almost invisible) |
setLineDashPattern(float[] pattern, float phase) |
d |
Alternating lengths of dash and gap. new float[] {} = solid |
setLineCapStyle(int) |
J |
Caps: 0 butt, 1 round, 2 projecting square (extends by half the width) |
setLineJoinStyle(int) |
j |
Joins: 0 miter, 1 round, 2 bevel |
setMiterLimit(float) |
M |
Limit beyond which a very sharp miter join is bevelled |
content.setLineWidth(1);
content.setLineDashPattern(new float[] { 6, 3 }, 0); // 6 pt dash, 3 pt gap: dashed
content.moveTo(Measures.cm(2), y);
content.lineTo(Measures.cm(17), y);
content.stroke();
content.setLineDashPattern(new float[] { 1, 2 }, 0); // 1 pt dash, 2 pt gap: dotted
content.moveTo(Measures.cm(2), y - Measures.cm(0.5f));
content.lineTo(Measures.cm(17), y - Measures.cm(0.5f));
content.stroke();
content.setLineDashPattern(new float[] {}, 0); // back to a solid line
content.setLineWidth(10); // thick lines to see the difference
for (int style = 0; style <= 2; style++) {
content.setLineCapStyle(style); // 0 = butt, 1 = round, 2 = square
content.setLineJoinStyle(style); // 0 = miter, 1 = round, 2 = bevel
float x = Measures.cm(3 + style * 5);
content.moveTo(x, y);
content.lineTo(x + Measures.cm(1.5f), y + Measures.cm(1.5f));
content.lineTo(x + Measures.cm(3), y);
content.stroke();
}- The pattern repeats along the whole path; the phase indicates the point in the pattern at which to start (useful so that two parallel lines don't have their gaps lined up).
- Dashed lines are ideal for the cut line of a tear-off slip ("cut here") or for subtle separators.
- Caps and joins are only noticeable with thick lines. For an invoice's tables and separators, the defaults (butt, miter) are fine.
- All these values are part of the graphics state and persist. If you change them in a helper method, wrap it with
saveGraphicsState/restoreGraphicsState.
Suggested widths for office documents:
| Element | Width |
|---|---|
| Inner lines of a table | 0.25-0.5 pt |
| Separators between sections | 0.5-0.75 pt |
| Border of a highlighted box | 1 pt |
| Decorative rule | 1.5-3 pt |
Colour: RGB, CMYK and greyscale
PDF works with colour spaces. The three basic ones are:
| Space | Components | What for | PDFBox method (fill) |
|---|---|---|---|
DeviceGray |
1: grey (0 = black, 1 = white) | Black-and-white text and lines | setNonStrokingColor(float g) |
DeviceRGB |
3: red, green, blue (0-1) | Screen, office printers | setNonStrokingColor(float r, float g, float b) or setNonStrokingColor(java.awt.Color) |
DeviceCMYK |
4: cyan, magenta, yellow, black (0-1) | Professional printing (four-colour process) | setNonStrokingColor(float c, float m, float y, float k) |
For the stroke colour the same methods exist under the name setStrokingColor. There's also a generic form, PDColor, which combines the components with their colour space:
// Four ways of expressing (almost) the same corporate blue
content.setNonStrokingColor(new Color(31, 58, 95)); // java.awt.Color: components 0-255
content.setNonStrokingColor(31 / 255f, 58 / 255f, 95 / 255f); // RGB: components 0-1
content.setNonStrokingColor(
new PDColor(new float[] { 0.12f, 0.23f, 0.37f }, PDDeviceRGB.INSTANCE)); // PDColor
content.setNonStrokingColor(0.67f, 0.39f, 0f, 0.63f); // CMYK: components 0-1
// Greyscale: eleven rectangles from black to white
for (int i = 0; i <= 10; i++) {
content.setNonStrokingColor(i / 10f);
content.addRect(Measures.cm(2 + i * 1.5f), y, Measures.cm(1.5f), Measures.cm(2));
content.fill();
}Points to bear in mind:
- Ranges:
java.awt.Coloruses integers from 0 to 255; thefloatmethods expect values from 0 to 1. If you pass31finstead of31 / 255f, PDFBox throwsIllegalArgumentException: Parameters must be within 0..1. java.awt.Coloris always written as RGB. It's the most convenient choice for office documents and the one InvoiceLab will use.- CMYK doesn't look the same on screen. When the PDF is opened, the viewer converts CMYK to RGB in its own way; the fourth square in the example comes out slightly different even though the numbers are "equivalent". If a document is going to a print shop, the printer will give you the brand's exact CMYK values; if it's going to a screen or an office printer, use RGB.
java.awt.Colorlives in Java'sjava.desktopmodule. It works fine on servers without a display (headless): it's just a data class.
The NebulaColors corporate palette
Repeating new Color(0x1F, 0x3A, 0x5F) throughout the code is fragile: a corporate rebrand would force you to hunt for numbers across the whole project. Let's centralize Nebula Distribution's palette in a constants class:
package com.invoicelab.pdf;
import java.awt.Color;
/** Nebula Distribution's corporate palette (RGB values for screen and office). */
public final class NebulaColors {
/** Corporate blue: header band, titles. #1F3A5F */
public static final Color BLUE = new Color(0x1F, 0x3A, 0x5F);
/** Very light blue for box backgrounds. #E8EEF5 */
public static final Color BACKGROUND_BLUE = new Color(0xE8, 0xEE, 0xF5);
/** Orange accent for highlighting (total, stamps). #E07A1F */
public static final Color ORANGE = new Color(0xE0, 0x7A, 0x1F);
/** Grey for secondary text and labels. #6B6B6B */
public static final Color TEXT_GREY = new Color(0x6B, 0x6B, 0x6B);
/** Light grey for separator lines. #C8C8C8 */
public static final Color LINE_GREY = new Color(0xC8, 0xC8, 0xC8);
private NebulaColors() {
}
}- The values are in hexadecimal (
0x1F), the format brand guidelines usually come in (#1F3A5F). Each constant's comment states its use, so that all documents are consistent. java.awt.Coloris immutable, so sharing these constants is safe.- The light colours (
BACKGROUND_BLUE,LINE_GREY) are for backgrounds and lines: a dark background behind black text makes reading harder and uses a lot of toner.
Transparency with PDExtendedGraphicsState
The basic colour operators have no transparency: everything is painted opaque. To draw semi-transparently you have to use an extended graphics state (ExtGState), a small dictionary stored in the page's resources and activated with the gs operator:
PDExtendedGraphicsState half = new PDExtendedGraphicsState();
half.setNonStrokingAlphaConstant(0.5f); // /ca: fill opacity (including text), 0-1
half.setStrokingAlphaConstant(0.5f); // /CA: stroke opacity
content.saveGraphicsState();
content.setGraphicsStateParameters(half); // writes "/gs1 gs" and registers the ExtGState on the page
// ... everything drawn here comes out at 50% opacity ...
content.restoreGraphicsState(); // back to opaqueThe lesson's example draws three overlapping red, green and blue circles at 50%: the shared areas blend the colours.
Practical rules:
- Always between
saveandrestore: there's no operator to "remove" transparency; you have to restore the previous state (or apply anotherExtGStatewith opacity 1). - Create the object once and reuse it throughout the document. PDFBox recognizes the same object and doesn't duplicate the resource on the page.
- Transparency affects text: it's how you make semi-transparent watermarks ("DRAFT", "COPY").
- PDF/A-1 forbids transparency. If we generate PDF/A-1b invoices in module 8, we won't be able to use it; PDF/A-2 and PDF/A-3 do allow it.
Rounded rectangles with Bézier curves
PDF has no operator for circles or rounded corners: they're built from Bézier curves. A quarter circle of radius r is approximated by a curve whose control points lie at a distance of r × 0.5523 from the end points, along the tangents. That constant, called kappa, equals 4 × (√2 − 1) / 3 ≈ 0.5522848 and produces an error of less than 0.03%, invisible to the naked eye.
A rounded rectangle is four straight sides plus four of those quarter circles:
(x+r, y2) ───────────── (x2−r, y2)
╱ ╲
(x, y2−r) (x2, y2−r)
│ │
(x, y+r) (x2, y+r)
╲ ╱
(x+r, y) ────────────── (x2−r, y)/** Constant for approximating a quarter circle with a Bézier curve. */
private static final float KAPPA = 0.5522848f;
/**
* Adds a rounded-corner rectangle to the current path (it doesn't paint it:
* you must then call fill(), stroke(), fillAndStroke() or clip()).
*/
public static void roundedRectPath(PDPageContentStream content, float x, float y,
float width, float height, float radius) throws IOException {
float r = Math.min(radius, Math.min(width, height) / 2); // the radius can't exceed half a side
float k = r * KAPPA; // distance of the control points
float x2 = x + width;
float y2 = y + height;
content.moveTo(x + r, y); // bottom, after the left corner
content.lineTo(x2 - r, y); // bottom side
content.curveTo(x2 - r + k, y, x2, y + r - k, x2, y + r); // bottom-right corner
content.lineTo(x2, y2 - r); // right side
content.curveTo(x2, y2 - r + k, x2 - r + k, y2, x2 - r, y2); // top-right corner
content.lineTo(x + r, y2); // top side
content.curveTo(x + r - k, y2, x, y2 - r + k, x, y2 - r); // top-left corner
content.lineTo(x, y + r); // left side
content.curveTo(x, y + r - k, x + r - k, y, x + r, y); // bottom-left corner
content.closePath();
}How to read each curveTo, taking the bottom-right corner as an example: the curve leaves (x2 − r, y) (the end of the bottom side) and arrives at (x2, y + r) (the start of the right side). The first control point (x2 − r + k, y) lies on the extension of the bottom side, and the second (x2, y + r − k) on the extension of the right side. That way the curve leaves and arrives tangent to the straight sides, with no kinks.
Note the method's design: it only builds the path. The caller decides whether to fill it, stroke it or use it for clipping. And a trick: if the radius is half the side of a square, the straight sides have zero length and the shape is a circle; that's how we draw the circles in the transparency example.
Clipping
A clipping region limits where painting can happen: anything outside it is discarded. You create one by building a path and calling clip() instead of painting it. PDFBox writes W n: "use this path as the clip" and "end the path without painting it".
// Diagonal stripes clipped to a rounded rectangle
content.saveGraphicsState(); // essential! clipping can only be undone with restore
Shapes.roundedRectPath(content, x, y, width, height, Measures.mm(5));
content.clip(); // W n
content.setStrokingColor(NebulaColors.BLUE);
content.setLineWidth(4);
for (float d = -height; d < width; d += 12) { // the stripes stick out: the clip cuts them off
content.moveTo(x + d, y);
content.lineTo(x + d + height, y + height);
}
content.stroke();
content.restoreGraphicsState(); // end of clippingIn business documents, clipping is useful for:
- Stopping text from spilling into the neighbouring cell of a table, as a visual alternative to the ellipsis from lesson 02-04 (although the hidden text is still in the PDF and can be copied).
- Fitting an image into a shape (a logo or a photo in a rounded frame, lesson 02-06).
- Decorative effects such as the stripes in the example.
// Text clipped to a 4 cm "cell"
content.saveGraphicsState();
content.addRect(xCell, yCell, cellWidth, Measures.cm(1));
content.clip();
content.beginText();
content.setFont(fonts.regular(), 10);
content.newLineAtOffset(xCell + 3, yCell + 10);
content.showText("Reference NEB-2026-ABCDEFGHIJKLMNOP"); // cut off at the edge of the cell
content.endText();
content.restoreGraphicsState();Rules: the clipping region can only shrink, never grow (each clip intersects with the previous one), and the only way to remove it is restoreGraphicsState(). That's why it always goes inside a save/restore pair.
The Shapes utility
Let's gather the operations the invoice will use again and again into a utility class. All its painting methods leave the graphics state untouched, following the rule from lesson 02-01:
package com.invoicelab.pdf;
import java.awt.Color;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
/** Reusable InvoiceLab graphics primitives. All of them leave the graphics state untouched. */
public final class Shapes {
/** Constant for approximating a quarter circle with a Bézier curve. */
private static final float KAPPA = 0.5522848f;
private Shapes() {
}
/** Horizontal line from x1 to x2 at height y. */
public static void horizontalLine(PDPageContentStream content, float x1, float x2, float y,
float lineWidth, Color color) throws IOException {
content.saveGraphicsState();
content.setStrokingColor(color);
content.setLineWidth(lineWidth);
content.moveTo(x1, y);
content.lineTo(x2, y);
content.stroke();
content.restoreGraphicsState();
}
/** (roundedRectPath: shown in the previous section) */
/**
* Box with a fill and/or a border (either colour may be null).
* radius = 0 for square corners.
*/
public static void drawBox(PDPageContentStream content, float x, float y, float width, float height,
float radius, Color fill, Color border, float borderWidth) throws IOException {
if (fill == null && border == null) {
return;
}
content.saveGraphicsState();
if (radius > 0) {
roundedRectPath(content, x, y, width, height, radius);
} else {
content.addRect(x, y, width, height);
}
if (fill != null) {
content.setNonStrokingColor(fill);
}
if (border != null) {
content.setStrokingColor(border);
content.setLineWidth(borderWidth);
}
if (fill != null && border != null) {
content.fillAndStroke();
} else if (fill != null) {
content.fill();
} else {
content.stroke();
}
content.restoreGraphicsState();
}
/**
* Creates a graphics state with opacity (0 = transparent, 1 = opaque) for fill and stroke.
* Create it once per document and reuse it with content.setGraphicsStateParameters(...).
*/
public static PDExtendedGraphicsState opacity(float alpha) {
PDExtendedGraphicsState state = new PDExtendedGraphicsState();
state.setNonStrokingAlphaConstant(alpha); // /ca: fill (including text)
state.setStrokingAlphaConstant(alpha); // /CA: strokes
return state;
}
}drawBoxcovers the four usual cases (background only, border only, both, with or without rounded corners) in a single call. Usingnullfor "no fill" or "no border" keeps the signature simple.opacityonly creates the object; it doesn't apply it. That way the caller can create it once and apply it wherever needed, inside its ownsave/restore.
InvoiceLab example: corporate band, separators and totals box
It's time to draw the invoice's graphic elements:
- A 12 mm blue band across the top, full bleed (from edge to edge of the paper, outside the content box), with a thin orange rule below it and the company name and invoice number in white.
- Two grey separator lines between sections.
- The totals box, with a light blue background, a blue border and rounded corners, and the total highlighted.
- A semi-transparent "DRAFT" watermark, rotated 45°, like the ones documents carry before they're issued.
package com.invoicelab.examples;
import com.invoicelab.pdf.Alignment;
import com.invoicelab.pdf.ContentBox;
import com.invoicelab.pdf.NebulaColors;
import com.invoicelab.pdf.InvoiceLabFonts;
import com.invoicelab.pdf.Shapes;
import com.invoicelab.pdf.Measures;
import com.invoicelab.pdf.TextMetrics;
import java.awt.Color;
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.PDFont;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;
public class InvoiceGraphicElements {
public static void main(String[] args) throws IOException {
Files.createDirectories(Path.of("output"));
try (PDDocument document = new PDDocument()) {
InvoiceLabFonts fonts = new InvoiceLabFonts(document);
PDFont regular = fonts.regular();
PDFont bold = fonts.bold();
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
PDRectangle sheet = page.getMediaBox();
ContentBox box = ContentBox.invoice(sheet);
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
// 1) Corporate band: full bleed (edge to edge), 12 mm high, at the top
float bandHeight = Measures.mm(12);
Shapes.drawBox(content, 0, sheet.getHeight() - bandHeight, sheet.getWidth(), bandHeight,
0, NebulaColors.BLUE, null, 0);
// 1 mm orange rule under the band
Shapes.drawBox(content, 0, sheet.getHeight() - bandHeight - Measures.mm(1),
sheet.getWidth(), Measures.mm(1), 0, NebulaColors.ORANGE, null, 0);
// White text on the band, vertically centred using the cap height
float size = 11;
float yText = sheet.getHeight() - bandHeight / 2 - TextMetrics.capHeight(bold, size) / 2;
content.setNonStrokingColor(Color.WHITE);
TextMetrics.writeAligned(content, bold, size, "NEBULA DISTRIBUTION LTD.",
box.left(), yText, Alignment.LEFT);
TextMetrics.writeAligned(content, regular, size, "INVOICE F-2026-0001",
box.right(), yText, Alignment.RIGHT);
// 2) Separator lines between sections
float ySeparator = box.yFromTop(Measures.mm(45));
Shapes.horizontalLine(content, box.left(), box.right(), ySeparator,
0.75f, NebulaColors.LINE_GREY);
Shapes.horizontalLine(content, box.left(), box.right(), ySeparator - Measures.mm(60),
0.75f, NebulaColors.LINE_GREY);
// 3) Totals box: light blue background, blue border, rounded corners
float totalsWidth = Measures.mm(75);
float totalsHeight = Measures.mm(26);
float xTotals = box.right() - totalsWidth;
float yTotals = ySeparator - Measures.mm(60) - Measures.mm(5) - totalsHeight;
Shapes.drawBox(content, xTotals, yTotals, totalsWidth, totalsHeight, Measures.mm(3),
NebulaColors.BACKGROUND_BLUE, NebulaColors.BLUE, 1f);
float padding = Measures.mm(4);
float xLabel = xTotals + padding;
float xAmount = xTotals + totalsWidth - padding;
float yRow = yTotals + totalsHeight - padding - TextMetrics.ascent(regular, 9);
String[][] rows = { { "Taxable base", "1.234,50 €" }, { "VAT (21%)", "259,25 €" } };
content.setNonStrokingColor(NebulaColors.TEXT_GREY);
for (String[] row : rows) {
TextMetrics.writeAligned(content, regular, 9, row[0], xLabel, yRow, Alignment.LEFT);
TextMetrics.writeAligned(content, regular, 9, row[1], xAmount, yRow, Alignment.RIGHT);
yRow -= 13;
}
// Thin line inside the box and highlighted total
Shapes.horizontalLine(content, xLabel, xAmount, yRow + 6, 0.5f, NebulaColors.BLUE);
yRow -= 6;
content.setNonStrokingColor(NebulaColors.BLUE);
TextMetrics.writeAligned(content, bold, 12, "TOTAL", xLabel, yRow, Alignment.LEFT);
TextMetrics.writeAligned(content, bold, 12, "1.493,75 €", xAmount, yRow, Alignment.RIGHT);
// 4) Semi-transparent "DRAFT" watermark rotated 45° in the centre of the page
PDExtendedGraphicsState transparent = Shapes.opacity(0.12f);
content.saveGraphicsState();
content.setGraphicsStateParameters(transparent);
content.setNonStrokingColor(NebulaColors.ORANGE);
content.beginText();
content.setFont(bold, 80);
float watermarkWidth = TextMetrics.width(bold, 80, "DRAFT");
// Origin at the centre of the page, rotated 45°, then step back by half the text
Matrix m = Matrix.getRotateInstance(Math.toRadians(45), sheet.getWidth() / 2, sheet.getHeight() / 2);
m.translate(-watermarkWidth / 2, -TextMetrics.capHeight(bold, 80) / 2);
content.setTextMatrix(m);
content.showText("DRAFT");
content.endText();
content.restoreGraphicsState();
}
document.save("output/invoice-graphic-elements.pdf");
}
}
}The most interesting parts of the code:
- The band deliberately ignores the content box: "full-bleed" decorative elements run right to the edge of the paper. Bear in mind that many office printers leave a few millimetres unprinted, so important text should never sit against the edge; that's why the text on the band does respect
box.left()andbox.right(). - Vertical centring with the cap height (lesson 02-04): the baseline is placed at the centre of the band minus half the cap height, and the text ends up optically centred.
- Painting order: first the box background, then the text on top. If you reverse it, the background covers the text.
- The text colour is changed with
setNonStrokingColorbefore each group and stays in effect until the next change;Shapesdoesn't alter it because it restores the state. - The watermark combines three techniques: opacity with
ExtGState, rotation with the text matrix, and centring with measurements.Matrix.translateon the rotated matrix moves within the already rotated system, which is why stepping back by "half the text" centres it along the diagonal. Adding watermarks to existing PDFs is covered in lesson 04-02.
Common Mistakes and Tips
- Building the path and not painting it. Without
stroke(),fill()orclip(), nothing is visible, and the pending path gets mixed up with the next one. - Mixing up stroke and fill colours.
setStrokingColoris for lines and outlines;setNonStrokingColorfor fills and text. If "the colour doesn't change", you're probably using the other one. - Passing 0-255 values to the
floatmethods. Thefloatvalues go from 0 to 1; for 0-255 usejava.awt.Color. - Drawing shapes inside
beginText()/endText(). Close the text first. - Forgetting
restoreGraphicsState()after aclip()or transparency. Everything that follows will be clipped or semi-transparent. - Painting the background after the text. Whatever is painted last ends up on top.
- Creating a new
PDExtendedGraphicsStatefor every use. Create it once per document and reuse it. - Using
setLineWidth(0). It produces the thinnest line the device can draw, almost invisible on a professional press. Use 0.25 pt as a minimum. - Tip: encapsulate each graphic element in a method that saves and restores the state; that way you can reorder the code without side effects.
Exercises
- Cut line for a tear-off slip. At 9 cm from the bottom edge of an A4 page, draw a dashed line (4 pt dash, 3 pt gap) from one side of the content box to the other in
TEXT_GREY, with the text "✂ Cut here" in 7 pt just above it, left-aligned (DejaVu Sans has the scissors glyph). - Rounded badge. Write a method
badge(PDPageContentStream content, PDFont font, String text, float x, float y)that draws a "pill" (a rectangle whose radius is half its height) with anORANGEbackground and the text in 8 pt white, centred vertically and horizontally, with 3 mm of horizontal padding. Use it to write "PAID" and "OVERDUE". - Check icon. Draw a green circle 1 cm in diameter (use
roundedRectPath) and, on top of it, a white check mark made of two segments (moveTo/lineTo), with a 2 pt width and round caps and joins.
Solutions
Solution 1.
float y = Measures.cm(9);
content.saveGraphicsState();
content.setStrokingColor(NebulaColors.TEXT_GREY);
content.setLineWidth(0.75f);
content.setLineDashPattern(new float[] { 4, 3 }, 0);
content.moveTo(box.left(), y);
content.lineTo(box.right(), y);
content.stroke();
content.restoreGraphicsState(); // the line goes back to solid
content.setNonStrokingColor(NebulaColors.TEXT_GREY);
TextMetrics.writeAligned(content, fonts.regular(), 7, "✂ Cut here",
box.left(), y + Measures.mm(1.5f), Alignment.LEFT);The dash pattern is restored by restoreGraphicsState(), with no need for setLineDashPattern(new float[] {}, 0). With Helvetica, the ✂ character would throw an exception: it isn't in WinAnsi.
Solution 2.
static void badge(PDPageContentStream content, PDFont font, String text, float x, float y)
throws IOException {
float size = 8;
float padding = Measures.mm(3);
float height = Measures.mm(6);
float width = TextMetrics.width(font, size, text) + 2 * padding;
Shapes.drawBox(content, x, y, width, height, height / 2, NebulaColors.ORANGE, null, 0);
float yBase = y + height / 2 - TextMetrics.capHeight(font, size) / 2;
content.saveGraphicsState();
content.setNonStrokingColor(Color.WHITE);
TextMetrics.writeAligned(content, font, size, text, x + width / 2, yBase, Alignment.CENTER);
content.restoreGraphicsState();
}
// Usage
badge(content, fonts.bold(), "PAID", box.left(), Measures.cm(15));
badge(content, fonts.bold(), "OVERDUE", box.left() + Measures.cm(3), Measures.cm(15));The width of the pill depends on the text, which is why it's measured before drawing. With a radius equal to half the height, the ends are semicircular. The text is written between save/restore so the white doesn't affect whatever comes next.
Solution 3.
float d = Measures.cm(1);
float x = Measures.cm(3), y = Measures.cm(10); // lower-left corner of the circle
Shapes.drawBox(content, x, y, d, d, d / 2, new Color(0x2E, 0x8B, 0x57), null, 0);
content.saveGraphicsState();
content.setStrokingColor(Color.WHITE);
content.setLineWidth(2);
content.setLineCapStyle(1); // round caps
content.setLineJoinStyle(1); // round join
content.moveTo(x + d * 0.28f, y + d * 0.52f);
content.lineTo(x + d * 0.44f, y + d * 0.34f); // short stroke, downwards
content.lineTo(x + d * 0.74f, y + d * 0.68f); // long stroke, upwards
content.stroke();
content.restoreGraphicsState();Expressing the coordinates as fractions of the diameter (d * 0.28f) means the icon can be scaled by changing a single variable. Another option would be to draw it at (0, 0) with size 1 and apply transform with a translation and a scale, as in lesson 02-01; in that case remember that the line width would be scaled too.
Conclusion
You now know how to draw in PDF: you build paths with moveTo, lineTo, curveTo, closePath and addRect, and you paint them with stroke, fill or fillAndStroke, controlling width, dashes, caps and joins. You work with RGB, CMYK and grey colours and know when to use each, you apply transparency with PDExtendedGraphicsState, you build rounded corners and circles with Bézier curves and the kappa constant, and you restrict drawing with clipping regions. The NebulaColors palette and the Shapes utility are now part of InvoiceLab, and the invoice has its corporate band, its separators and its totals box.
Only one visual piece is missing to complete the invoice header: Nebula Distribution's logo. In the next and final lesson of the module we'll learn to insert JPEG and PNG images (with transparency), to scale them without distortion, to reuse them across several pages without duplicating their size and to generate them on the fly, and we'll put together the complete invoice header.
PDF Generation and Editing with Apache PDFBox
Module 1: PDF and PDFBox Fundamentals
- The PDF Format and Apache PDFBox
- Setting Up the Project with PDFBox 3
- Anatomy of a PDF: COS Objects, Pages and Resources
- Your First PDF: Creating, Saving and Loading Documents
- Debugging Tools: PDFDebugger and the Command Line
Module 2: Generating Content
- Pages and the Coordinate System
- Writing Text with PDPageContentStream and Standard Fonts
- Embedded TrueType Fonts and Unicode
- Text Layout: Measuring, Aligning and Wrapping Lines
- Vector Graphics: Lines, Shapes and Colours
- Inserting Images
Module 3: Business Documents
- Building Tables from Scratch
- Multi-Page Documents: Pagination, Headers and Footers
- Barcodes and QR Codes
- Designing a Reusable Document Generator
- Project: the Complete Invoice
Module 4: Editing Existing PDFs
- Load, Modify and Save: Full and Incremental Saves
- Adding Content to Existing Pages: Stamps and Watermarks
- Page Manipulation: Inserting, Removing, Rotating and Reordering
- Merging and Splitting Documents
- Overlays, Layers and Optional Content
- Document Metadata: Info and XMP
Module 5: AcroForm Forms
- Introduction to AcroForm Forms
- Reading and Filling In Forms
- Creating Forms Programmatically
- Form Appearances and Flattening
Module 6: Extraction and Analysis
- Extracting Text with PDFTextStripper
- Area-Based Extraction and Text Positions
- Extracting Images and Resources
- Rendering Pages to Images
- Bookmarks, Links and Annotations
Module 7: Security and Digital Signatures
- Encryption and Permissions
- Digital Signatures: Concepts and PDF Structure
- Signing Documents with PDFBox and Bouncy Castle
- Verifying Signatures and Visible Signatures
