The invoice header already has its corporate band, aligned text and boxes, but it's missing the element that identifies a company more than any other: its logo. In this lesson you'll learn how PDF stores images (as external objects, XObjects, drawn through the CTM), how to create them in PDFBox from files, from the classpath or from a BufferedImage generated on the fly, the difference between JPEGFactory and LosslessFactory, how a PNG's transparency is preserved, how to scale images without distorting them, why you should reuse the same image on every page, and how resolution and format affect file size. We'll finish the module by putting together the complete invoice header with the InvoiceHeader class.
Contents
- How PDF stores an image: the Image XObject
- Nebula Distribution's logo (generated with Java2D)
- Creating a
PDImageXObject: from a file, from bytes and from the classpath JPEGFactoryandLosslessFactory- Formats and transparency: JPEG, PNG and the soft mask (SMask)
- Drawing with
drawImageand scaling proportionally - The
Imagesutility - Reusing the same image across several pages
- Resolution, DPI and file size
- Rotated and clipped images, and SVG
- Project: the complete invoice header
How PDF stores an image: the Image XObject
In lesson 01-03 you saw that a page has a /Resources dictionary with fonts and other resources. Images are one of them: they're stored as an image XObject, an independent stream with the compressed pixels and a dictionary describing its width, height, colour space and compression. The page only contains a reference by name (/Im1) and the Do operator that draws it:
q
170.08 0 0 56.69 51.02 708.66 cm % CTM: scales the image to 170 x 57 pt and places it at (51, 709)
/Im1 Do % draws the /Im1 XObject
QThe key is in the first line: an image is always drawn into a 1 × 1 unit square, and it's the transformation matrix (CTM, lesson 02-01) that scales it to the desired size and positions it. PDFBox's drawImage writes exactly these operators for you.
Consequences of this model:
- The image's size in pixels and the size at which it's drawn on the page are independent. A 720 × 240 pixel image can take up 2 cm or 20 cm.
- Since it's a separate object, the same image can be drawn many times (on several pages, or several times on the same page) while storing its pixels only once.
- Images are drawn outside text objects: calling
drawImagebetweenbeginText()andendText()throwsIllegalStateException: Error: drawImage is not allowed within a text block.
Nebula Distribution's logo (generated with Java2D)
InvoiceLab's convention (lesson 01-02) is to store images in src/main/resources/img/, and the logo is called logo-nebula.png. Since Nebula Distribution is fictitious, it doesn't have a real logo, so we'll generate it with code. It's also a good example of a technique you'll use on other occasions: creating images on the fly with BufferedImage and Java2D (charts, stamps, thumbnails).
package com.invoicelab.examples;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.imageio.ImageIO;
/**
* Generates Nebula Distribution's fictitious logo (PNG with a transparent background)
* in src/main/resources/img/logo-nebula.png. Run it once from the project root.
*/
public class GenerateNebulaLogo {
public static void main(String[] args) throws IOException, FontFormatException {
int width = 720, height = 240; // pixels: 3:1 aspect ratio
BufferedImage logo = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = logo.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Color blue = new Color(0x1F, 0x3A, 0x5F);
Color orange = new Color(0xE0, 0x7A, 0x1F);
// Symbol: a blue circle (the "nebula") with an orange orbit
g.setColor(blue);
g.fill(new Ellipse2D.Float(30, 40, 160, 160));
g.setColor(orange);
g.setStroke(new BasicStroke(12));
g.draw(new Ellipse2D.Float(10, 95, 200, 50));
// Wordmark: text in the project's corporate font
Font bold = loadFont("/fonts/DejaVuSans-Bold.ttf");
Font regular = loadFont("/fonts/DejaVuSans.ttf");
g.setColor(blue);
g.setFont(bold.deriveFont(96f));
g.drawString("NEBULA", 230, 140);
g.setColor(new Color(0x6B, 0x6B, 0x6B));
g.setFont(regular.deriveFont(34f));
g.drawString("DISTRIBUTION", 236, 190);
g.dispose();
Path target = Path.of("src/main/resources/img/logo-nebula.png");
Files.createDirectories(target.getParent());
ImageIO.write(logo, "png", target.toFile());
System.out.println("Logo generated: " + target + " (" + Files.size(target) + " bytes)");
}
private static Font loadFont(String resource) throws IOException, FontFormatException {
try (InputStream in = GenerateNebulaLogo.class.getResourceAsStream(resource)) {
if (in == null) {
throw new IOException("Cannot find " + resource);
}
return Font.createFont(Font.TRUETYPE_FONT, in);
}
}
}How it works:
TYPE_INT_ARGB: each pixel has an alpha (transparency) channel. A newBufferedImageof this type starts out fully transparent, so the logo won't have a white background and can be placed on top of any colour.createGraphics()returns aGraphics2Dfor drawing with the Java2D API (shapes, text, gradients). We turn on antialiasing to smooth the edges. When we're done,dispose()releases its resources.Font.createFontloads the same DejaVu Sans we use in the PDF (lesson 02-03), so the logo doesn't depend on the fonts installed on the system.ImageIO.write(..., "png", ...)saves it as PNG, a lossless format that preserves transparency.- We've made it 720 × 240 pixels: in the resolution section we'll see why that size is enough to print it 6 cm wide with good quality.
Run it once from the project root (mvn compile exec:java -Dexec.mainClass=com.invoicelab.examples.GenerateNebulaLogo or from your IDE) and you'll get logo-nebula.png (about 16 KB). If your company has a real logo, just copy its PNG to that path.
Creating a PDImageXObject: from a file, from bytes and from the classpath
The class that represents an image in PDFBox is PDImageXObject. Just like embedded fonts, it belongs to a document (its data will be written into that file), so all the creation methods take the PDDocument.
| Method | Source | Comment |
|---|---|---|
PDImageXObject.createFromFile(String path, PDDocument doc) |
File on disk | Infers the format from the extension (JPG, PNG, GIF, BMP, TIFF) |
PDImageXObject.createFromFileByContent(File f, PDDocument doc) |
File on disk | Infers the format by reading the first bytes (useful if the extension isn't reliable) |
PDImageXObject.createFromByteArray(PDDocument doc, byte[] bytes, String name) |
Bytes in memory | Detects the format from the content. The name is only used in error messages. The most versatile: database, classpath, HTTP request |
JPEGFactory.createFromStream(PDDocument doc, InputStream in) |
A JPEG | Embeds the JPEG as is, without decompressing it |
JPEGFactory.createFromImage(PDDocument doc, BufferedImage img, float quality) |
BufferedImage |
Compresses to JPEG at the given quality (0-1) |
LosslessFactory.createFromImage(PDDocument doc, BufferedImage img) |
BufferedImage |
Lossless compression (Flate), preserves transparency |
From a file is the simplest:
PDImageXObject logo = PDImageXObject.createFromFile("src/main/resources/img/logo-nebula.png", document);
System.out.printf("Logo: %d x %d px, %d bits/component, mask: %s%n",
logo.getWidth(), logo.getHeight(), logo.getBitsPerComponent(), logo.getSoftMask() != null);
// Logo: 720 x 240 px, 8 bits/component, mask: trueBut in a real application the src/main/resources/... path doesn't exist once the JAR has been packaged. As with fonts, the project's images are read from the classpath, and createFromByteArray is perfect for that: we read the resource's bytes and PDFBox detects the format. We'll wrap this up in the Images utility in a moment.
getWidth() and getHeight() return the size in pixels, not points. That's the data we need to calculate proportions.
JPEGFactory and LosslessFactory
When the image is in memory as a BufferedImage (generated on the fly, resized or processed), you have to choose how to compress it inside the PDF:
JPEGFactory.createFromImage |
LosslessFactory.createFromImage |
|
|---|---|---|
| Compression | JPEG (DCT), lossy | Flate (like ZIP/PNG), lossless |
| Configurable quality | Yes (0 = lowest, 1 = highest) | Not needed: it's exact |
| Transparency | Yes: the alpha channel is stored separately as a mask | Yes: the alpha channel is stored separately as a mask |
| Ideal for | Photographs, gradients, colour scans | Logos, charts, screenshots, text, flat colours |
| Problem if misused | On logos and text it produces "noise" around the edges | On photographs it produces huge files |
And if you already have a JPEG file, don't read it as a BufferedImage only to compress it again: you'd lose quality and time. Use createFromFile, createFromByteArray or JPEGFactory.createFromStream, which embed the original JPEG bytes without recompressing them.
For comparison, let's generate a synthetic "photo" (a gradient with thousands of coloured dots, which behaves like a real photograph) and embed it in three ways in a one-page PDF:
BufferedImage photo = new BufferedImage(800, 500, BufferedImage.TYPE_INT_RGB);
Graphics2D g = photo.createGraphics();
g.setPaint(new GradientPaint(0, 0, new Color(0x1F, 0x3A, 0x5F), 800, 500, new Color(0xE0, 0x7A, 0x1F)));
g.fillRect(0, 0, 800, 500);
Random random = new Random(42);
for (int i = 0; i < 4000; i++) {
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256), 60));
g.fillOval(random.nextInt(800), random.nextInt(500), 6, 6);
}
g.dispose();
PDImageXObject jpeg = JPEGFactory.createFromImage(document, photo, 0.8f); // lossy
PDImageXObject lossless = LosslessFactory.createFromImage(document, photo); // losslessPhoto JPEG quality 0.8 50,932 bytes
Photo JPEG quality 0.5 27,331 bytes
Photo lossless 180,983 bytesFor a photograph, the 80% JPEG is 3.5 times smaller than the lossless version and they look identical to the naked eye. A quality between 0.75 and 0.85 is a good balance for documents.
Formats and transparency: JPEG, PNG and the soft mask (SMask)
| Source format | Transparency? | How PDFBox embeds it |
|---|---|---|
| JPEG | No | As is (DCTDecode filter), without recompressing |
| PNG without transparency | No | Lossless (FlateDecode); where possible, it copies the PNG's compressed data without decoding it |
| PNG with transparency | Yes | Lossless + SMask |
| GIF, BMP | GIF: simple transparency | Decoded with ImageIO and embedded losslessly |
| Black-and-white TIFF (CCITT, typical of scanners and fax) | No | As is (CCITTFaxDecode filter), very compact |
An important technical detail: PDF images have no alpha channel. Pixels are always stored as RGB, grey or CMYK, and transparency is stored as a second greyscale image, the soft mask (/SMask), where black is transparent and white is opaque. That's why our logo reports mask: true. PDFBox creates the SMask automatically when loading a PNG with transparency or when using an ARGB BufferedImage; you don't have to do anything, but it's worth knowing for three reasons:
- If you draw the logo on the blue band, you'll see its shape, not a white rectangle.
- An image with transparency takes up more space (it's two images).
- PDF/A-1 forbids SMasks (they're transparency). If we generate PDF/A-1b in module 8, we'll need a logo without transparency (on a white background). PDF/A-2 and PDF/A-3 do allow them.
Drawing with drawImage and scaling proportionally
PDPageContentStream offers several variants:
| Method | Effect |
|---|---|
drawImage(image, x, y) |
Draws with 1 pixel = 1 point (that is, as if the image were 72 dpi) |
drawImage(image, x, y, width, height) |
Draws the image fitted to that width and height in points |
drawImage(image, Matrix matrix) |
Draws with an arbitrary matrix (rotation, skew) |
(x, y) is always the image's lower-left corner, consistent with the PDF coordinate system.
The first variant is a trap: our 720-pixel logo would measure 720 points, 25.4 cm, wider than an A4 page! You'll almost always use the second one, and the most typical mistake is passing a width and height that don't respect the image's aspect ratio, which distorts it:
// Right: fixed width of 60 mm and proportional height
float width = Measures.mm(60);
float height = width * logo.getHeight() / logo.getWidth(); // 60 mm × 240 / 720 = 20 mm
content.drawImage(logo, Measures.mm(20), Measures.mm(250), width, height);
// Wrong: 60 x 30 mm for an image with a 3:1 ratio → logo "stretched" vertically
content.drawImage(logo, Measures.mm(110), Measures.mm(250), Measures.mm(60), Measures.mm(30));The most common case in layout is: "the logo must fit in a box of at most A × B mm, without being distorted". It's the same problem CSS solves with object-fit: contain: you calculate the scale that makes the image fit by width and the one that makes it fit by height, and take the smaller one.
scale = min(maxWidth / widthPx, maxHeight / heightPx)
width = widthPx × scale
height = heightPx × scaleFor the logo (720 × 240 px) in a 40 × 40 mm box: scaling by width gives 40 mm wide and 13.3 mm high; scaling by height would give 120 mm wide, which doesn't fit. The smaller wins: the logo is drawn at 40 × 13.3 mm.
The Images utility
Let's gather loading from the classpath, proportional fitting and the resolution calculation into a utility class:
package com.invoicelab.pdf;
import java.io.IOException;
import java.io.InputStream;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
/** Utilities for loading and placing images. */
public final class Images {
/** Size in points at which an image is drawn. */
public record Size(float width, float height) {
}
private Images() {
}
/** Loads an image from the classpath (for example "/img/logo-nebula.png") for this document. */
public static PDImageXObject loadResource(PDDocument document, String path) throws IOException {
try (InputStream in = Images.class.getResourceAsStream(path)) {
if (in == null) {
throw new IOException("Image not found on the classpath: " + path);
}
return PDImageXObject.createFromByteArray(document, in.readAllBytes(), path);
}
}
/** Largest size that fits in maxWidth x maxHeight while keeping the image's aspect ratio. */
public static Size fit(PDImageXObject image, float maxWidth, float maxHeight) {
float scale = Math.min(maxWidth / image.getWidth(), maxHeight / image.getHeight());
return new Size(image.getWidth() * scale, image.getHeight() * scale);
}
/**
* Draws the image fitted (without distortion) into a box whose top-left corner is
* (x, yTop). The image is aligned to the top left of the box.
* @return the size at which it was drawn
*/
public static Size drawFitted(PDPageContentStream content, PDImageXObject image,
float x, float yTop, float maxWidth, float maxHeight)
throws IOException {
Size s = fit(image, maxWidth, maxHeight);
content.drawImage(image, x, yTop - s.height(), s.width(), s.height());
return s;
}
/** Effective resolution (pixels per inch) of an image drawn at this width in points. */
public static float dpi(PDImageXObject image, float drawnWidth) {
return image.getWidth() / (drawnWidth / 72f);
}
}loadResourcefollows the same pattern asInvoiceLabFonts: classpath, anullcheck with a clear message, andtry-with-resources.fitonly calculates;drawFittedalso draws and returns the size used. LikeTextBlock, it takes the box's top edge (we think from the top down) and returns the space it took up so we can keep laying out below it.dpicalculates the effective resolution, which we'll look at shortly.- The
Sizerecord is more readable than returning a two-elementfloat[].
Reusing the same image across several pages
A ten-page invoice carries the logo on every page. There are two ways of doing this, and only one is correct:
// WRONG: a new PDImageXObject on each page → the pixels are stored ten times
for (int i = 0; i < 10; i++) {
PDImageXObject logo = Images.loadResource(document, "/img/logo-nebula.png");
// ... draw on page i ...
}
// RIGHT: a single PDImageXObject created once and drawn on every page
PDImageXObject logo = Images.loadResource(document, "/img/logo-nebula.png");
for (int i = 0; i < 10; i++) {
// ... draw 'logo' on page i ...
}Nine times bigger through a simple oversight! With a single object, each page only adds a reference to the same image stream to its resources. The rule is the same as with fonts:
- One image per document, created once and reused on all its pages.
- Never share a
PDImageXObjectbetween different documents (it belongs to the document that created it). If you generate many invoices, cache the PNG's bytes, not thePDImageXObject, just as we did with fonts.
Resolution, DPI and file size
A PDF has no resolution, but images do: their effective resolution depends on how many pixels are spread over the space they take up on the page. It's measured in dpi (dots per inch, also called PPI):
Our 720-pixel logo drawn at 60 mm (170 pt, 2.36 inches) has 720 / 2.36 ≈ 305 dpi.
| Document use | Recommended resolution |
|---|---|
| Screen only (email, web portal) | 150 dpi |
| Office printer | 200-300 dpi |
| Professional printing | 300 dpi |
| Black-and-white text scans | 300 dpi (1 bit per pixel) |
Practical consequences:
- Below the recommended resolution, the image will look pixelated when printed. A 200-pixel logo at 6 cm (85 dpi) looks blurry.
- Above it, you only increase the PDF's size with no visible gain. A 4000 × 3000 pixel phone photo placed 5 cm wide has more than 2,000 dpi: resize it before embedding it.
- File size depends on the embedded pixels, not the drawn size. Scaling down a large image in
drawImagedoesn't make the file smaller.
To resize with Java2D before embedding:
static BufferedImage resize(BufferedImage original, int widthPx) {
int heightPx = Math.round((float) original.getHeight() * widthPx / original.getWidth());
BufferedImage target = new BufferedImage(widthPx, heightPx, BufferedImage.TYPE_INT_RGB);
Graphics2D g = target.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.drawImage(original, 0, 0, widthPx, heightPx, null);
g.dispose();
return target;
}
// A product photo that will be shown 5 cm wide at 200 dpi: 5 / 2.54 × 200 ≈ 394 pixels
PDImageXObject product = JPEGFactory.createFromImage(document, resize(originalPhoto, 394), 0.8f);TYPE_INT_RGB discards transparency (appropriate for photos going to JPEG); for a PNG with transparency you'd use TYPE_INT_ARGB and LosslessFactory.
Rotated and clipped images, and SVG
Rotating an image
The drawImage(image, Matrix) variant takes the full matrix. Remember that the image occupies a 1 × 1 square, so the matrix must include the scaling to the desired size:
Images.Size s = Images.fit(logo, Measures.mm(50), Measures.mm(50));
Matrix m = Matrix.getRotateInstance(Math.toRadians(15), Measures.mm(30), Measures.mm(150)); // rotate and position
m.scale(s.width(), s.height()); // scale
content.drawImage(logo, m);Clipping an image to a shape
With the clipping from the previous lesson you can fit an image into a rounded or circular frame; you'll practise this in exercise 2.
What about SVG?
PDFBox can't embed SVG images directly: createFromFile doesn't recognize the format. Many corporate logos are delivered as SVG, so you have three alternatives:
| Option | Pros | Cons |
|---|---|---|
| Convert the SVG to a high-resolution PNG (at build time, with Inkscape or a similar tool) | Simple, no dependencies | Loses vector quality (at 300 dpi it isn't noticeable) |
Draw the SVG with Apache Batik onto a Graphics2D that generates PDF operators (the pdfbox-graphics2d project) |
Keeps the vectors | Heavy dependencies and another API to learn |
Redraw the logo with PDF paths (moveTo, curveTo… lesson 02-05) |
Vector and dependency-free | Only practical for very simple logos |
For InvoiceLab we go with the first: a PNG of sufficient resolution in src/main/resources/img/.
Project: the complete invoice header
It's time to bring together everything we've learned in the module. The header of Nebula Distribution's invoices will have:
flowchart TB
B["Full-bleed blue band (12 mm) + orange rule · website and phone in white, on the right"]
subgraph F1["Top row (inside the content box)"]
direction LR
L["Fitted logo<br/>max. 55 x 20 mm"] ~~~ T["INVOICE (22 pt, blue)<br/>No. F-2026-0001<br/>Date: 15/01/2026<br/>right-aligned"]
end
subgraph F2["Details row"]
direction LR
E["ISSUER<br/>company name in bold<br/>VAT ID, address, email"] ~~~ C["CUSTOMER (rounded light blue box)<br/>company name in bold<br/>VAT ID, address"]
end
S["Grey separator line · returns the Y where the content continues"]
B --> F1 --> F2 --> S
All the logic is encapsulated in the InvoiceHeader class in the com.invoicelab.pdf package. For now, the data reaches it in a small nested record; in module 3, when we create the model (Invoice, Customer), we'll get it from there.
package com.invoicelab.pdf;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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.image.PDImageXObject;
/**
* Invoice header: corporate band, logo, title with number and date,
* and the issuer and customer data blocks.
*/
public final class InvoiceHeader {
/** Data the header needs (in module 3 it will come from the Invoice model). */
public record Data(String number, String date, List<String> issuer, List<String> customer) {
}
private static final float BAND_HEIGHT = Measures.mm(12);
private static final float RULE_HEIGHT = Measures.mm(1);
private static final float LOGO_MAX_WIDTH = Measures.mm(55);
private static final float LOGO_MAX_HEIGHT = Measures.mm(20);
private static final float DATA_SIZE = 9.5f;
private static final float LABEL_SIZE = 7.5f;
private static final float PADDING = Measures.mm(4); // inner padding of the customer box
private final InvoiceLabFonts fonts;
private final PDImageXObject logo;
public InvoiceHeader(InvoiceLabFonts fonts, PDImageXObject logo) {
this.fonts = fonts;
this.logo = logo;
}
/**
* Draws the complete header.
* @return the Y coordinate from which the page content can continue
*/
public float draw(PDPageContentStream content, PDRectangle sheet, ContentBox box, Data data)
throws IOException {
PDFont regular = fonts.regular();
PDFont bold = fonts.bold();
// 1) Full-bleed corporate band with an orange rule
float yBand = sheet.getUpperRightY() - BAND_HEIGHT;
Shapes.drawBox(content, sheet.getLowerLeftX(), yBand, sheet.getWidth(), BAND_HEIGHT,
0, NebulaColors.BLUE, null, 0);
Shapes.drawBox(content, sheet.getLowerLeftX(), yBand - RULE_HEIGHT, sheet.getWidth(), RULE_HEIGHT,
0, NebulaColors.ORANGE, null, 0);
content.setNonStrokingColor(Color.WHITE);
float yBandText = yBand + BAND_HEIGHT / 2 - TextMetrics.capHeight(regular, 8) / 2;
TextMetrics.writeAligned(content, regular, 8, "www.nebula.example · 976 000 000",
box.right(), yBandText, Alignment.RIGHT);
// 2) Top row: logo on the left; title, number and date on the right
float yRow = box.top();
Images.Size logoSize = Images.drawFitted(content, logo, box.left(), yRow,
LOGO_MAX_WIDTH, LOGO_MAX_HEIGHT);
float yTitle = yRow - TextMetrics.ascent(bold, 22);
content.setNonStrokingColor(NebulaColors.BLUE);
TextMetrics.writeAligned(content, bold, 22, "INVOICE", box.right(), yTitle, Alignment.RIGHT);
content.setNonStrokingColor(Color.BLACK);
float yNumber = yTitle - TextMetrics.descent(bold, 22) - Measures.mm(2)
- TextMetrics.ascent(bold, 10);
TextMetrics.writeAligned(content, bold, 10, "No. " + clean(bold, data.number()),
box.right(), yNumber, Alignment.RIGHT);
float yDate = yNumber - 10 * 1.4f;
TextMetrics.writeAligned(content, regular, 10, "Date: " + clean(regular, data.date()),
box.right(), yDate, Alignment.RIGHT);
float rowHeight = Math.max(logoSize.height(), yRow - yDate + TextMetrics.descent(regular, 10));
float y = yRow - rowHeight - Measures.mm(8);
// 3) Issuer (left) and customer (right, in a box) blocks
float gap = Measures.mm(8);
float columnWidth = (box.width() - gap) / 2;
float xCustomer = box.left() + columnWidth + gap;
float issuerHeight = dataBlock(content, "ISSUER", data.issuer(), box.left(), y,
columnWidth, false);
float innerWidth = columnWidth - 2 * PADDING;
float customerHeight = measureDataBlock(data.customer(), innerWidth) + 2 * PADDING;
Shapes.drawBox(content, xCustomer, y - customerHeight, columnWidth, customerHeight, Measures.mm(2),
NebulaColors.BACKGROUND_BLUE, null, 0);
dataBlock(content, "CUSTOMER", data.customer(), xCustomer + PADDING, y - PADDING, innerWidth, true);
y -= Math.max(issuerHeight, customerHeight) + Measures.mm(6);
// 4) Closing separator of the header
Shapes.horizontalLine(content, box.left(), box.right(), y, 0.75f, NebulaColors.LINE_GREY);
return y - Measures.mm(4);
}
// ------------------------------------------------------------------ data blocks
/** Label + first line in bold + the rest in regular. Returns the height used up. */
private float dataBlock(PDPageContentStream content, String label, List<String> lines,
float x, float yTop, float width, boolean highlighted) throws IOException {
PDFont regular = fonts.regular();
PDFont bold = fonts.bold();
float y = yTop;
// Uppercase label, grey (or blue if highlighted) and letter-spaced
content.saveGraphicsState();
content.setNonStrokingColor(highlighted ? NebulaColors.BLUE : NebulaColors.TEXT_GREY);
content.setCharacterSpacing(1f);
float yLabel = y - TextMetrics.ascent(bold, LABEL_SIZE);
TextMetrics.writeAligned(content, bold, LABEL_SIZE, label, x, yLabel, Alignment.LEFT);
content.restoreGraphicsState();
y = yLabel - TextMetrics.descent(bold, LABEL_SIZE) - Measures.mm(1.5f);
// Company name in bold and the remaining lines in regular
content.setNonStrokingColor(Color.BLACK);
TextBlock companyName = new TextBlock(bold, DATA_SIZE + 0.5f, width);
y -= companyName.draw(content, clean(bold, lines.get(0)), x, y);
y -= Measures.mm(1);
TextBlock rest = new TextBlock(regular, DATA_SIZE, width).lineSpacing(1.35f);
y -= rest.draw(content, join(regular, lines.subList(1, lines.size())), x, y);
return yTop - y;
}
/** Same geometry as dataBlock, but without drawing. */
private float measureDataBlock(List<String> lines, float width) throws IOException {
PDFont regular = fonts.regular();
PDFont bold = fonts.bold();
return TextMetrics.ascent(bold, LABEL_SIZE) + TextMetrics.descent(bold, LABEL_SIZE)
+ Measures.mm(1.5f)
+ new TextBlock(bold, DATA_SIZE + 0.5f, width).measureHeight(clean(bold, lines.get(0)))
+ Measures.mm(1)
+ new TextBlock(regular, DATA_SIZE, width).lineSpacing(1.35f)
.measureHeight(join(regular, lines.subList(1, lines.size())));
}
private static String clean(PDFont font, String text) throws IOException {
return InvoiceLabFonts.sanitize(font, text);
}
/** Sanitizes each line and joins them with '\n' so TextBlock treats them as paragraphs. */
private static String join(PDFont font, List<String> lines) throws IOException {
List<String> cleaned = new ArrayList<>();
for (String line : lines) {
cleaned.add(clean(font, line));
}
return String.join("\n", cleaned);
}
}This code is a review of the whole module. Notice how each lesson contributes its piece:
| Lesson | Piece used in InvoiceHeader |
|---|---|
| 02-01 | Measures.mm(...), ContentBox (edges of the content box), coordinates from the top, save/restore |
| 02-02 | Text colour, character spacing in the labels |
| 02-03 | InvoiceLabFonts (embedded DejaVu) and sanitize for the data |
| 02-04 | TextMetrics (ascent, descent, right alignment) and TextBlock (long addresses that wrap on their own) |
| 02-05 | Shapes.drawBox, horizontalLine, NebulaColors |
| 02-06 | Images.drawFitted for the logo |
Design decisions:
- It receives its dependencies in the constructor (
InvoiceLabFontsand the logo, already created for the document). That way it follows the "fonts and images, once per document" rule: if the invoice has several pages in module 3, they'll all use the same objects. - It measures before drawing the customer block: the background box must be painted before the text (otherwise it would cover it), but its height depends on the text.
measureDataBlockreproduces the same geometry asdataBlockwithout drawing, usingTextBlock.measureHeight. - Long addresses don't break the design: since each block uses
TextBlockwith the column width, an address that doesn't fit wraps onto two lines and the box grows with it. - It sanitizes all data before measuring or drawing it: a tab in the customer's address won't stop invoicing.
- It returns the Y where the content can continue: the same contract as
TextBlock.draw, on a larger scale.
And the program that uses it:
package com.invoicelab.examples;
import com.invoicelab.pdf.InvoiceHeader;
import com.invoicelab.pdf.ContentBox;
import com.invoicelab.pdf.InvoiceLabFonts;
import com.invoicelab.pdf.Images;
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 java.util.List;
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.graphics.image.PDImageXObject;
public class InvoiceHeaderDemo {
public static void main(String[] args) throws IOException {
Files.createDirectories(Path.of("output"));
InvoiceHeader.Data data = new InvoiceHeader.Data(
"F-2026-0001",
"15/01/2026",
List.of("Nebula Distribution Ltd.",
"VAT ID: B00000000",
"12 Fictional Street, Unit 3",
"50001 Zaragoza",
"[email protected]"),
List.of("Example Hardware Co.",
"VAT ID: J00000000",
"45 Test Avenue, Unit 2",
"22001 Huesca"));
try (PDDocument document = new PDDocument()) {
InvoiceLabFonts fonts = new InvoiceLabFonts(document);
PDImageXObject logo = Images.loadResource(document, "/img/logo-nebula.png");
InvoiceHeader header = new InvoiceHeader(fonts, logo);
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
ContentBox box = ContentBox.invoice(page.getMediaBox());
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
if (Boolean.getBoolean("invoicelab.grid")) {
ReferenceGrid.draw(content, page.getMediaBox());
}
float y = header.draw(content, page.getMediaBox(), box, data);
System.out.printf("The header extends down to y = %.1f (%.1f mm from the top edge)%n",
y, Measures.toMm(page.getMediaBox().getHeight() - y));
// In module 3, the table of invoice lines will start here
}
document.save("output/invoice-header.pdf");
}
}
}Open output/invoice-header.pdf: you'll see the blue band with the orange rule, the logo with its transparent background, the "INVOICE" title with the number and date right-aligned, the issuer's details on the left and the customer's in a light blue box with rounded corners, all closed off with a grey line. Run with -Dinvoicelab.grid=true to check the measurements against the grid. The 88.7 mm it takes up leave almost 19 cm of the content box free for what's coming in module 3.
Common Mistakes and Tips
- Using
drawImage(image, x, y)without a size. It draws at 1 pixel = 1 point, usually huge. Always specify the size. - Distorting the image by passing a width and height that don't respect its aspect ratio. Use
Images.fitordrawFitted. - Creating the
PDImageXObjectinside the page loop. It multiplies the PDF's size. One image per document, reused. - Sharing a
PDImageXObjectbetween documents. It belongs to its document; cache the bytes, not the object. - Disk paths in production (
src/main/resources/...). They don't exist inside the JAR: load from the classpath. - Using
LosslessFactoryfor photos (huge files) orJPEGFactoryfor logos (noisy edges). Each type of image has its own compression. - Recompressing a JPEG by reading it as a
BufferedImage. Embed it as is withcreateFromFile,createFromByteArrayorJPEGFactory.createFromStream. - Embedding 4000-pixel photos to show them at 5 cm. Resize them first to the resolution you need (150-300 dpi).
- Calling
drawImageinsidebeginText()/endText(). It throwsIllegalStateException. - Tip: calculate and log the effective resolution (
Images.dpi) of images that come from users; if it's below 150 dpi, warn that it will print pixelated.
Exercises
- Logo on every page. Generate a 3-page A4 PDF with the logo in the top-right corner of the content box (fitted into 30 × 12 mm) and the text "Page N of 3" below it, right-aligned. Use PDFDebugger (lesson 01-05) to check that the document contains a single image XObject.
- Photo in a rounded frame. Write a method
drawCover(PDPageContentStream content, PDImageXObject image, float x, float y, float width, float height, float radius)that completely fills a rounded rectangle with the image, without distorting it and clipping whatever is left over (likeobject-fit: coverin CSS), centring the image in the frame. - Choosing the compression. Write a method
createImage(PDDocument document, BufferedImage image, boolean isPhotograph)that usesJPEGFactory(quality 0.85) for photographs without transparency andLosslessFactoryin every other case. Add another methodwarnIfLowResolution(PDImageXObject image, float drawnWidth)that prints a warning to the console if the effective resolution is below 150 dpi.
Solutions
Solution 1.
try (PDDocument document = new PDDocument()) {
InvoiceLabFonts fonts = new InvoiceLabFonts(document);
PDImageXObject logo = Images.loadResource(document, "/img/logo-nebula.png"); // ONCE
int total = 3;
for (int n = 1; n <= total; n++) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
ContentBox box = ContentBox.invoice(page.getMediaBox());
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
Images.Size s = Images.fit(logo, Measures.mm(30), Measures.mm(12));
float xLogo = box.right() - s.width(); // flush with the right edge
content.drawImage(logo, xLogo, box.top() - s.height(), s.width(), s.height());
float yText = box.top() - s.height() - Measures.mm(2) - TextMetrics.ascent(fonts.regular(), 8);
TextMetrics.writeAligned(content, fonts.regular(), 8, "Page " + n + " of " + total,
box.right(), yText, Alignment.RIGHT);
}
}
document.save("output/logo-three-pages.pdf");
}drawFitted (which aligns to the left) won't do for right-aligning the logo, so we use fit and calculate x by subtracting the width from the right edge. In PDFDebugger you'll see that the /Resources of all three pages point to the same /Im1 object. Real "Page N of M" numbering, with the total known only at the end, will be tackled in module 3.
Solution 2.
static void drawCover(PDPageContentStream content, PDImageXObject image, float x, float y,
float width, float height, float radius) throws IOException {
// "cover": the LARGER of the two scales, so the image covers the whole frame
float scale = Math.max(width / image.getWidth(), height / image.getHeight());
float imageWidth = image.getWidth() * scale;
float imageHeight = image.getHeight() * scale;
content.saveGraphicsState();
Shapes.roundedRectPath(content, x, y, width, height, radius);
content.clip(); // anything sticking out of the frame won't be visible
content.drawImage(image,
x + (width - imageWidth) / 2, // centred horizontally
y + (height - imageHeight) / 2, // centred vertically
imageWidth, imageHeight);
content.restoreGraphicsState(); // removes the clipping
}The only difference from fit is using Math.max instead of Math.min: with the larger scale, the image covers the whole frame and sticks out on one side, and the clipping takes care of hiding the excess. With radius equal to half of a square frame you'll get a circular photo, like the ones in user profiles.
Solution 3.
static PDImageXObject createImage(PDDocument document, BufferedImage image, boolean isPhotograph)
throws IOException {
boolean hasTransparency = image.getColorModel().hasAlpha();
if (isPhotograph && !hasTransparency) {
return JPEGFactory.createFromImage(document, image, 0.85f);
}
return LosslessFactory.createFromImage(document, image);
}
static void warnIfLowResolution(PDImageXObject image, float drawnWidth) {
float dpi = Images.dpi(image, drawnWidth);
if (dpi < 150) {
System.out.printf("WARNING: the %d px image drawn at %.1f mm only has %.0f dpi; "
+ "it will look pixelated when printed%n", image.getWidth(), Measures.toMm(drawnWidth), dpi);
}
}There's no reliable way to tell whether a BufferedImage "is a photo" by looking at its pixels, so the caller indicates it (usually they know from the source: product photos versus logos or charts). Although JPEGFactory can store transparency as a mask, we prefer LosslessFactory for images with alpha because they tend to be logos or graphics with sharp edges. In a real application, the warning would go to the log (lesson 01-02) rather than the console.
Conclusion
This lesson wraps up module 2. You know that a PDF image is an XObject drawn into a unit square scaled by the CTM; you create it from a file, bytes or the classpath with PDImageXObject, or from a BufferedImage with JPEGFactory (photos) and LosslessFactory (logos and graphics); you understand how transparency is stored in an SMask; you scale it without distortion with Images.fit; you reuse it on every page with a single object; and you control its resolution and size. You've also generated Nebula Distribution's logo with Java2D.
Let's review the whole module: you've mastered the coordinate system, units and the CTM (Measures, ContentBox, ReferenceGrid); you write text with PDF operators and the standard fonts; you embed Unicode fonts (InvoiceLabFonts, FallbackText); you measure, align, justify and wrap text (TextMetrics, TextBlock); you draw lines, shapes, colours and transparency (Shapes, NebulaColors); you insert images (Images), and you've brought all those pieces together in InvoiceHeader, the complete header of invoice F-2026-0001. With the header finished, Nebula Distribution's invoice now has a visual identity, but it's still missing its essential part: the lines with the products, quantities, prices and amounts. In module 3 we'll build tables from scratch on top of this module's pieces (measuring, aligning, wrapping text, drawing lines and backgrounds) and, from there, pagination, QR codes and the complete invoice generator.
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
