In the previous lessons we've taken PDFs apart into pieces: text, positions, images and fonts. Now we'll do the opposite: look at them whole, as a person would see them, by turning each page into an image. That's what a PDF viewer does, and PDFBox offers it through the PDFRenderer class. We'll use it for three of Nebula Distribution's needs: generating the thumbnails that the intranet shows next to each invoice and batch, checking how optional content layers look on screen and on paper, and visually comparing two versions of a document to find out what has changed. Along the way we'll look at the issues that cause the most trouble in production: memory, concurrency and fonts missing from the server.
Contents
PDFRenderer: from page toBufferedImage- Scale, resolution and image types
- Saving as PNG or JPEG
- Thumbnails for the intranet:
Thumbnails - Rendering onto a
Graphics2D: the contact sheet RenderDestinationand optional content- Memory: one page at a time and subsampling
- Performance and concurrency
- Fonts missing from the server
- Printing
- Visual comparison of two PDFs:
VisualComparator
PDFRenderer: from page to BufferedImage
We already used PDFRenderer in lesson 03-03 to read QR codes. Its basic usage is:
try (PDDocument document = Loader.loadPDF(new File("output/F-2026-0001.pdf"))) {
PDFRenderer renderer = new PDFRenderer(document);
BufferedImage image = renderer.renderImageWithDPI(0, 150, ImageType.RGB); // page 1, 150 dpi
ImageIO.write(image, "png", new File("output/render/p1-150.png"));
}new PDFRenderer(document)is cheap; create one per document and reuse it for all its pages.- The first parameter is the 0-based page index, like
getPage. - The result is an ordinary
java.awt.image.BufferedImage: you can save it, scale it, pass it to ZXing or display it in a Swing application. - The renderer respects the CropBox (it only paints the visible area) and
/Rotate(the Transport invoice comes out in landscape), and it draws annotations using their stored appearances. As we saw in 05-04, it ignoresNeedAppearances: a form field with no appearance shows up empty (for some comment annotations, such as the highlights in 06-05, it does generate an appearance on the fly).
It's the same thing the
rendersubcommand ofpdfbox-appthat we used in lesson 01-05 does, now from our own code.
Scale, resolution and image types
PDFRenderer has two families of methods, which differ only in how you express the size:
| Method | Size | A4 page (595 × 842 pt) |
|---|---|---|
renderImage(page) |
Scale 1: one pixel per point (72 dpi) | 595 × 841 px |
renderImage(page, scale) |
scale pixels per point |
scale 2 → 1190 × 1683 px |
renderImageWithDPI(page, dpi) |
dpi / 72 pixels per point |
150 dpi → 1240 × 1753 px |
renderImage(page, scale, type, destination) |
Plus image type and destination | — |
The relationship is simple: scale = dpi / 72. Sizes are truncated (842 × 1 = 841.89 → 841 px), so two "identical" pages from different documents can differ by one pixel if their boxes aren't exactly the same.
Typical resolutions:
| Use | Resolution |
|---|---|
| Thumbnail | Scale calculated for a fixed width (100–300 px) |
| On-screen view | 72–110 dpi |
| Reading QR codes/barcodes | 150 dpi (on our invoice, the QR code can also be read at 72 dpi) |
| OCR | 300 dpi |
| High-quality printing | 300–600 dpi |
The image type determines the colours and the memory. Values measured with the first page of F-2026-0001.pdf at 150 dpi (1240 × 1753 = 2.17 million pixels):
ImageType |
BufferedImage |
Approximate memory | Use |
|---|---|---|---|
BINARY |
TYPE_BYTE_BINARY (1 bit per pixel) |
0.27 MB | Fax, OCR of black-and-white documents |
GRAY |
TYPE_BYTE_GRAY (1 byte) |
2.2 MB | Greyscale thumbnails, OCR, codes |
RGB |
TYPE_INT_RGB (4 bytes) |
8.7 MB | The usual choice |
ARGB |
TYPE_INT_ARGB (4 bytes) |
8.7 MB | Transparent background (for compositing onto another image) |
BGR |
TYPE_3BYTE_BGR (3 bytes) |
6.5 MB | Some computer vision libraries |
With ARGB the page background isn't painted: in the Supplies invoice, pixel (0, 0) has alpha 0. With the other types, the background is white.
Do the maths before choosing a resolution: an A4 page at 300 dpi in RGB takes up about 35 MB of memory (2480 × 3508 × 4 bytes). Ten threads doing the same thing add up to 350 MB.
Saving as PNG or JPEG
ImageIO.write(image, "png", file) is enough for PNG. For JPEG you'll want to control the quality, and ImageIO.write doesn't allow that; you need an ImageWriter. We wrap it in the Thumbnails utility class in the com.invoicelab.extraction package:
/** Saves as PNG (lossless: ideal for text and for comparisons). */
public static void savePng(BufferedImage image, Path target) throws IOException {
if (!ImageIO.write(image, "png", target.toFile())) {
throw new IOException("No PNG writer for " + target);
}
}
/** Saves as JPEG with the given quality (0.0 = lowest, 1.0 = highest). RGB or GRAY images only. */
public static void saveJpeg(BufferedImage image, Path target, float quality) throws IOException {
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
params.setCompressionQuality(quality);
Files.deleteIfExists(target);
try (ImageOutputStream output = ImageIO.createImageOutputStream(target.toFile())) {
writer.setOutput(output);
writer.write(null, new IIOImage(image, null, null), params);
} finally {
writer.dispose();
}
}ImageIO.writereturnsfalse(without an exception) if it can't find a writer able to save that image in that format. That's why we check it.MODE_EXPLICITindicates that we'll set the quality ourselves.Files.deleteIfExistsis needed becausecreateImageOutputStreamdoesn't truncate a longer existing file.writer.dispose()releases the encoder's native resources.
Sizes obtained with the same page at 150 dpi:
| Format | Size |
|---|---|
| JPEG quality 0.5 | 195 KB |
| JPEG quality 0.8 | 283 KB |
| JPEG quality 0.95 | 468 KB |
| PNG | 284 KB |
For pages with lots of text and flat backgrounds, PNG competes with JPEG and has no artefacts around the letters. JPEG wins with photographs and scans. For small thumbnails, JPEG at 0.8 is a good balance.
Watch out with ARGB and JPEG: JPEG doesn't support transparency. With an
ARGBimage,ImageIO.write(image, "jpg", …)returnsfalseand creates nothing, and oursaveJpegthrowsIIOException: Bogus input colorspace. Render inRGBif you're going to save as JPEG.
Thumbnails for the intranet: Thumbnails
Nebula's intranet shows a 200-pixel-wide thumbnail per page next to each document. Instead of a fixed resolution, we calculate the scale from the desired width:
/** One JPEG thumbnail per page, 'widthPx' pixels wide. Renders page by page. */
public static List<Path> generate(Path pdf, Path folder, int widthPx) throws IOException {
Files.createDirectories(folder);
String base = pdf.getFileName().toString().replaceFirst("\\.pdf$", "");
List<Path> files = new ArrayList<>();
try (PDDocument document = Loader.loadPDF(pdf.toFile())) {
PDFRenderer renderer = new PDFRenderer(document);
renderer.setSubsamplingAllowed(true); // huge images: read with subsampling
for (int i = 0; i < document.getNumberOfPages(); i++) {
PDRectangle box = document.getPage(i).getCropBox();
boolean rotated = document.getPage(i).getRotation() % 180 != 0;
float widthPoints = rotated ? box.getHeight() : box.getWidth();
float scale = widthPx / widthPoints; // scale 1 = 72 dpi (1 point = 1 pixel)
BufferedImage image = renderer.renderImage(i, scale, ImageType.RGB);
Path target = folder.resolve("%s-%02d.jpg".formatted(base, i + 1));
saveJpeg(image, target, 0.8f);
files.add(target);
// 'image' is no longer used after this point: the garbage collector can free it before the next page
}
}
return files;
}- The visible width of a page rotated by 90° is the height of its CropBox. Without this correction, the Transport thumbnail (landscape) would come out with the scale of a portrait page.
- Each page is rendered, saved and discarded before moving on to the next: the memory needed is that of one page, not of the whole document (we'll come back to this).
- We'll explain
setSubsamplingAllowed(true)in the section on memory.
With the January batch we get 14 files, batch-2026-01-01.jpg … -14.jpg, between 1.5 KB (the blank sheets) and 14 KB.
Rendering onto a Graphics2D: the contact sheet
As well as returning images, PDFRenderer can paint onto a Graphics2D that you supply: that of a larger BufferedImage, a Swing component or a printer. We'll take advantage of this for a "contact sheet" with all the pages of the batch in a single image:
/** "Contact sheet": all the pages in a grid, drawn directly onto a Graphics2D. */
public static BufferedImage contactSheet(PDDocument document, int columns, int cellWidth) throws IOException {
PDRectangle a4 = PDRectangle.A4;
float scale = cellWidth / a4.getWidth();
int cellHeight = Math.round(a4.getHeight() * scale);
int pages = document.getNumberOfPages();
int rows = (pages + columns - 1) / columns;
int margin = 10;
BufferedImage sheet = new BufferedImage(columns * (cellWidth + margin) + margin,
rows * (cellHeight + margin) + margin, BufferedImage.TYPE_INT_RGB);
Graphics2D g = sheet.createGraphics();
try {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(0xDD, 0xDD, 0xDD));
g.fillRect(0, 0, sheet.getWidth(), sheet.getHeight());
PDFRenderer renderer = new PDFRenderer(document);
for (int i = 0; i < pages; i++) {
int x = margin + (i % columns) * (cellWidth + margin);
int y = margin + (i / columns) * (cellHeight + margin);
Graphics2D cell = (Graphics2D) g.create(x, y, cellWidth, cellHeight); // origin at the cell
try {
cell.setBackground(Color.WHITE); // renderPageToGraphics calls clearRect with this colour
renderer.renderPageToGraphics(i, cell, scale);
} finally {
cell.dispose();
}
}
} finally {
g.dispose();
}
return sheet;
}g.create(x, y, width, height)creates a childGraphics2Dwhose origin is at the corner of the cell and which clips anything that goes outside it. That way the renderer doesn't need to know anything about the grid.renderPageToGraphics(index, graphics, scale)paints the page at that scale.- A trap we ran into while writing this example: the first version painted the cell white with
fillRect, and the result came out with every page black.renderPageToGraphicsstarts by callingclearRect, which fills with theGraphics2D's background colour (setBackground), not the drawing colour, and the default background colour of aBufferedImageis black. The fix issetBackground(Color.WHITE). - Every
Graphics2Dyou create must be released withdispose(); thetry/finallyblocks guarantee it even if there's an exception.
RenderDestination and optional content
In lesson 04-05 we created F-2026-0001-layers.pdf with several layers: "Original" (visible), "Customer copy" (hidden) and "Print mark", configured with Layers.printOnly so that it only appears on paper. There we mentioned that PDFBox's renderer respects that configuration. The fourth parameter of renderImage states what you're rendering for:
PDFRenderer renderer = new PDFRenderer(document);
BufferedImage screen = renderer.renderImage(0, 1f, ImageType.RGB, RenderDestination.VIEW);
BufferedImage paper = renderer.renderImage(0, 1f, ImageType.RGB, RenderDestination.PRINT);
BufferedImage export = renderer.renderImage(0, 1f, ImageType.RGB, RenderDestination.EXPORT);| Destination | Optional content it uses | In F-2026-0001-layers.pdf |
|---|---|---|
VIEW |
Each group's /Usage /View |
«ORIGINAL» |
PRINT |
/Usage /Print |
«ORIGINAL» + «Printed copy: uncontrolled» |
EXPORT |
/Usage /Export (if absent, the group's default state) |
Same as PRINT in this document |
Not specified (null) |
getDefaultDestination(), which is null by default |
Same as EXPORT |
Comparing the images at 72 dpi, VIEW and PRINT differ by 436 pixels (the print mark's text); PRINT, EXPORT and the call without a destination produce identical images. Practical conclusion: for on-screen thumbnails, always specify RenderDestination.VIEW, or your users will see marks intended only for paper. You can set it once with renderer.setDefaultDestination(RenderDestination.VIEW). The "Customer copy" layer, which is switched off in the document, doesn't appear for any destination.
Related: renderer.setAnnotationsFilter(filter) decides which annotations are painted. For example, a -> !(a instanceof PDAnnotationText) renders without the sticky notes we'll add in lesson 06-05.
Memory: one page at a time and subsampling
Rendering is the PDFBox operation that uses the most memory. The basic rules:
- One page at a time: render, save or process, and discard. Never accumulate the images of all the pages of a large document in a list.
- Just the resolution you need: doubling the dpi quadruples the memory.
GRAYorBINARYwhen colour doesn't matter (OCR, codes).- Subsampling of large images:
renderer.setSubsamplingAllowed(true).
Subsampling deserves an explanation. A scanned PDF can contain a 5000 × 7000 pixel image on an A4 page. For a 200-pixel-wide thumbnail, decoding all 35 million pixels is a waste. With subsampling enabled, PDFBox reads the image skipping rows and columns (for example, one pixel in every 8) when the target resolution is much lower than the image's. The result is indistinguishable in a thumbnail and much faster. It's disabled by default because it reduces quality if you then enlarge the image; enable it for thumbnails, not for OCR.
Another related setting is setImageDownscalingOptimizationThreshold(float), which controls when a higher-quality (and slower) scaling is applied to images that are reduced a lot. Memory management for the document itself (stream caches, temporary files) is covered in lesson 08-03.
Performance and concurrency
Rendering a 14-page batch at 150 dpi takes about 340 ms on our test machine. For hundreds of documents it's tempting to use several threads, but there's one rule you can't break:
A
PDDocumentis not thread-safe. Neither isPDFRenderernorPDFTextStripper. Two threads rendering pages of the samePDDocumentat the same time can produce corrupted images or random exceptions.
The right solution is for each thread to have its own document. If the PDF is in memory as a byte[], loading it several times is cheap:
byte[] batch = Files.readAllBytes(Path.of("output/batch-2026-01.pdf"));
ExecutorService threads = Executors.newFixedThreadPool(4);
List<Future<BufferedImage>> tasks = new ArrayList<>();
for (int i = 0; i < 14; i++) {
int page = i;
tasks.add(threads.submit(() -> {
try (PDDocument own = Loader.loadPDF(batch)) { // one document per task
return new PDFRenderer(own).renderImageWithDPI(page, 150, ImageType.RGB);
}
}));
}
for (Future<BufferedImage> t : tasks) {
BufferedImage image = t.get(); // this is where you'd save it
}
threads.shutdown();Loader.loadPDF(byte[])loads from memory. Each task loads, renders its page and closes.- Loading the document 14 times has a cost, but it's small compared with rendering. In our test, with 4 threads the time dropped from 344 ms to 121 ms.
- If you're processing many different documents, it's even simpler: one document per task, with nothing shared.
- Remember memory: 4 threads at 150 dpi in RGB means 4 × 8.7 MB in images alone.
Fonts missing from the server
In 06-03 we saw that the Supplies and Transport invoices use Helvetica and Times without embedding them. To render them, PDFBox needs the glyphs from somewhere. The FontMapper component looks for them like this:
- If the font is embedded, it uses it. That's the case for all InvoiceLab invoices.
- If not, it searches the fonts installed on the system for an equivalent. For the 14 standard fonts it has a list of known substitutes.
- If it finds nothing, it uses LiberationSans-Regular, which ships inside the PDFBox jar itself as a last resort.
You can ask which font it will use:
FontMapping<?> mapping = FontMappers.instance().getFontBoxFont("Times-Roman", null);
System.out.println(mapping.getFont().getName() + " fallback=" + mapping.isFallback());On our Linux test machine, Helvetica → LiberationSans, Helvetica-Bold → LiberationSans-Bold and Times-Roman → LiberationSerif, all with fallback=false ("good" substitutes, with the same metrics). In a minimal Docker container with no fonts installed, Times would end up as LiberationSans: the invoice would be displayed in a sans-serif font and, if the PDF uses bold or characters the substitute doesn't have, with incorrect widths or glyphs.
Recommendations for servers:
- Install a basic font package in the server image (for example,
fonts-liberationandfonts-dejavuon Debian/Ubuntu). - The first time it needs to look up system fonts, PDFBox scans them all and stores the result in the
.pdfbox.cachecache file in the user's home directory; that first scan can take several seconds. In containers, make sure the directory is writable, or point to another one with thepdfbox.fontcachesystem property. - For the PDFs that you generate, always embed the fonts (02-03): it's the only guarantee that they'll look the same everywhere.
Printing
PDFBox integrates with Java's printing API (java.awt.print). The simplest way:
try (PDDocument document = Loader.loadPDF(new File("output/F-2026-0001.pdf"))) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setJobName("F-2026-0001");
job.setPageable(new PDFPageable(document)); // respects each page's size and orientation
if (job.printDialog()) { // system dialog (leave it out on a server)
job.print();
}
}PDFPageableadapts the document to Java'sPageableinterface: each page with its own size.- To scale to a specific paper size, use
new PDFPrintable(document, Scaling.SHRINK_TO_FIT)andjob.setPrintable(...). - When printing, PDFBox renders with
RenderDestination.PRINT, so the "Print mark" from 04-05 does appear on paper. - On a headless server,
printDialog()isn't available; you choose the printer withjob.setPrintService(...).
Visual comparison of two PDFs: VisualComparator
Two PDFs can be very different inside (reordered objects, compression, dates in the metadata) and look exactly the same. Conversely, a one-line change in the content stream can shift half an invoice. The most reliable way to know whether two documents look the same is to render them and compare the pixels. In lesson 08-05 we'll turn this into automated tests; here we build the tool:
public static List<Result> compare(Path a, Path b, float dpi, int tolerance, Path mapsFolder)
throws IOException {
Files.createDirectories(mapsFolder);
List<Result> results = new ArrayList<>();
try (PDDocument docA = Loader.loadPDF(a.toFile()); PDDocument docB = Loader.loadPDF(b.toFile())) {
if (docA.getNumberOfPages() != docB.getNumberOfPages()) {
throw new IllegalArgumentException("Different page count: %d versus %d"
.formatted(docA.getNumberOfPages(), docB.getNumberOfPages()));
}
PDFRenderer rA = new PDFRenderer(docA);
PDFRenderer rB = new PDFRenderer(docB);
for (int i = 0; i < docA.getNumberOfPages(); i++) {
BufferedImage imgA = rA.renderImageWithDPI(i, dpi, ImageType.RGB);
BufferedImage imgB = rB.renderImageWithDPI(i, dpi, ImageType.RGB);
if (imgA.getWidth() != imgB.getWidth() || imgA.getHeight() != imgB.getHeight()) {
throw new IllegalArgumentException("Page " + (i + 1) + " has a different size");
}
BufferedImage map = new BufferedImage(imgA.getWidth(), imgA.getHeight(), BufferedImage.TYPE_INT_RGB);
long different = 0;
for (int y = 0; y < imgA.getHeight(); y++) {
for (int x = 0; x < imgA.getWidth(); x++) {
int pa = imgA.getRGB(x, y);
int pb = imgB.getRGB(x, y);
if (differs(pa, pb, tolerance)) {
different++;
map.setRGB(x, y, 0xFF0000); // red: difference
} else {
map.setRGB(x, y, lighten(pa)); // heavily lightened original
}
}
}
Path file = null;
if (different > 0) {
file = mapsFolder.resolve("differences-%02d.png".formatted(i + 1));
Thumbnails.savePng(map, file);
}
results.add(new Result(i + 1, different, (long) imgA.getWidth() * imgA.getHeight(), file));
}
}
return results;
}The helper pieces of the VisualComparator class are simple:
record Result(int page, long different, long total, Path map)with apercentage()method.differs(a, b, tolerance)extracts the three channels of each pixel with bit shifts ((rgb >> 16) & 0xFFis red,>> 8green and no shift blue) and returnstrueif any of them differs by more than the tolerance.lighten(rgb)moves each channel towards white so that, in the map, the original document appears faint and the differences in red stand out.
The tolerance is important: the antialiasing of letter edges can vary slightly between versions of Java or PDFBox. A tolerance of 10–20 per channel ignores those variations and detects the real changes.
Let's try it with the original invoice and the one stamped as "PAID" in lesson 04-02:
for (VisualComparator.Result r : VisualComparator.compare(Path.of("output/F-2026-0001.pdf"),
Path.of("output/F-2026-0001-paid.pdf"), 72, 16, Path.of("output/differences"))) {
System.out.printf("page %d: %,d of %,d pixels different (%.2f%%) %s%n", r.page(), r.different(),
r.total(), r.percentage(), r.map() == null ? "" : "-> " + r.map());
}page 1: 2,746 of 500,395 pixels different (0.55%) -> output/differences/differences-01.png
page 2: 0 of 500,395 pixels different (0.00%)The difference map shows the lightened invoice with the "PAID" stamp in red, in the customer area; page 2 is identical. This kind of comparison detects regressions that no text analysis would catch: a displaced logo, a table overlapping the footer, a substituted font.
Common Mistakes and Tips
- Page indexes:
renderImageis 0-based, likegetPage. - Confusing scale and dpi:
renderImage(0, 150)isn't 150 dpi, it's a scale of 150 (10,800 dpi)! UserenderImageWithDPIfor dpi, or divide by 72. - On-screen thumbnails with print marks: specify
RenderDestination.VIEW. - Saving ARGB as JPEG: it fails (
falseorIIOException). Use RGB. - Not checking the result of
ImageIO.write: it may write nothing without throwing an exception. - Black background with
renderPageToGraphics: setsetBackground(Color.WHITE)on theGraphics2D. - Sharing a
PDDocumentbetween threads: one document per thread, always. - Accumulating all the pages in memory: render, save and discard.
- Servers without fonts: PDFs with non-embedded fonts will look different. Install basic fonts and check with
FontMappers. - Tip: for thumbnails of scanned documents, enable
setSubsamplingAllowed(true)and useImageType.GRAY; you'll gain speed and memory without losing anything visible.
Exercises
- Thumbnails by height. For the first page of each supplier invoice (Supplies, Stationery and Transport), generate a greyscale PNG thumbnail 300 pixels high, whatever the page orientation.
- How much does the print layer change? Refactor
VisualComparatorto have a public methodcountDifferences(BufferedImage, BufferedImage, int tolerance)and use it to compareF-2026-0001-layers.pdfrendered withVIEWand withPRINTat 72 dpi, with tolerance 0 and 16. - Thumbnails in parallel. Write
List<Path> generateInParallel(List<Path> pdfs, Path folder, int widthPx, int threads)that generates the thumbnails of several PDFs at once, one document per task, reusingThumbnails.generate.
Solutions
Solution 1.
for (String f : List.of("supplies-SF-2026-0412", "stationery-PI-000873", "transport-2026-017")) {
try (PDDocument d = Loader.loadPDF(new File("output/suppliers/" + f + ".pdf"))) {
PDPage page = d.getPage(0);
boolean rotated = page.getRotation() % 180 != 0;
float heightPoints = rotated ? page.getCropBox().getWidth() : page.getCropBox().getHeight();
BufferedImage img = new PDFRenderer(d).renderImage(0, 300f / heightPoints, ImageType.GRAY);
Thumbnails.savePng(img, Path.of("output/grey-thumbnails/" + f + ".png"));
System.out.println(f + ": " + img.getWidth() + "x" + img.getHeight());
}
}Result: Supplies and Stationery, 212 × 300; Transport, 424 × 300 (landscape). For a rotated page, the visible height is the width of the CropBox. Create the folder beforehand with Files.createDirectories. The greyscale PNGs take up between 2.7 and 4.1 KB: greyscale reduces the size a lot in text documents.
Solution 2.
public static long countDifferences(BufferedImage a, BufferedImage b, int tolerance) {
long n = 0;
for (int y = 0; y < a.getHeight(); y++) {
for (int x = 0; x < a.getWidth(); x++) {
if (differs(a.getRGB(x, y), b.getRGB(x, y), tolerance)) {
n++;
}
}
}
return n;
}
try (PDDocument d = Loader.loadPDF(new File("output/F-2026-0001-layers.pdf"))) {
PDFRenderer r = new PDFRenderer(d);
BufferedImage view = r.renderImage(0, 1f, ImageType.RGB, RenderDestination.VIEW);
BufferedImage print = r.renderImage(0, 1f, ImageType.RGB, RenderDestination.PRINT);
System.out.println(VisualComparator.countDifferences(view, print, 0) + " / "
+ VisualComparator.countDifferences(view, print, 16));
}Result: 436 pixels with tolerance 0 and 367 with tolerance 16. The difference between the two figures is the pixels on the antialiased edge of the text, whose colour is very close to the background. With the method extracted, the loop in compare boils down to calling countDifferences (and painting the map), and you'll be able to compare images that don't come from a PDF, such as a reference capture stored in the module 8 tests.
Solution 3.
public static List<Path> generateInParallel(List<Path> pdfs, Path folder, int widthPx, int threads)
throws IOException {
ExecutorService executor = Executors.newFixedThreadPool(threads);
try {
List<Future<List<Path>>> tasks = new ArrayList<>();
for (Path pdf : pdfs) {
tasks.add(executor.submit(() -> Thumbnails.generate(pdf, folder, widthPx))); // opens its own document
}
List<Path> all = new ArrayList<>();
for (Future<List<Path>> t : tasks) {
all.addAll(t.get());
}
return all;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted", e);
} catch (ExecutionException e) {
throw new IOException("Error generating thumbnails", e.getCause());
} finally {
executor.shutdown();
}
}Thumbnails.generate already follows the golden rule: it loads its own PDDocument, uses it and closes it, without sharing anything with other tasks. Files.createDirectories is safe even if several tasks call it at the same time. ExecutionException wraps the task's original exception; we unwrap it with getCause() so as not to lose the message. Choose the number of threads with memory in mind, not just the number of cores.
Conclusion
In this lesson you've learned to turn pages into images with PDFRenderer: to choose scale, resolution and image type while calculating the memory they consume, to save as PNG or as JPEG with controlled quality, to generate thumbnails that respect each page's orientation, and to paint onto your own Graphics2D without falling into the black-background trap. You know that RenderDestination decides which optional content layers are visible, that a PDDocument isn't shared between threads, how PDFBox substitutes non-embedded fonts and why that matters on a server. With Thumbnails and VisualComparator, InvoiceLab now generates the intranet thumbnails and can tell what has changed, visually, between two versions of a document.
In the last lesson of the module we'll go back to modifying documents, but this time to make them navigable: we'll add bookmarks to the monthly batch from 04-04 with one entry per invoice, links from the cover's index and named destinations, and we'll use the text positions from 06-02 to highlight the total detected on the supplier invoices with an annotation.
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
