So far we've modified the content of existing pages. In this lesson we change the structure of the document: which pages it has, in what order, and with what size and orientation. These are operations that Nebula Distribution's accounts department asks for all the time: "add the general terms and conditions at the end of this invoice", "I want the original and the customer copy interleaved", "rotate the scanned page that's sideways", "this American letter-size document needs to become A4". You'll learn to work with the PDPageTree page tree, to duplicate pages without side effects, to import pages from another document while being aware of the pitfalls, and to crop and scale pages. Everything will end up in the Pages utility class of the com.invoicelab.editing package.
Contents
- The page tree and
PDPageTree - Adding, inserting and removing pages
- Rotating pages
- Reordering and moving pages
- Duplicating a page within the same document
- Importing a page from another document:
importPageand its problems - Cropping with the CropBox
- Scaling a page: changing the MediaBox and transforming the content
- Blank pages for double-sided printing
- The
Pagesutility and the example program
The page tree and PDPageTree
Remember from lesson 01-03 that pages aren't stored in a simple list: they hang from a tree whose root is the catalog's /Pages dictionary. Each intermediate node (/Type /Pages) has a /Kids array and a /Count counter; each leaf is a page (/Type /Page) with a /Parent reference to its parent node.
flowchart TB
CAT["Catalog"] --> R["/Pages (root)<br/>/Count 5"]
R --> P1["Page 1"]
R --> N["/Pages (intermediate)<br/>/Count 3"]
R --> P5["Page 5"]
N --> P2["Page 2"]
N --> P3["Page 3"]
N --> P4["Page 4"]
PDFBox generates flat trees (every page hangs from the root), but third-party documents often have intermediate nodes. Fortunately you don't have to walk the tree by hand: the PDPageTree class (which you get with document.getPages()) presents it as an ordered sequence.
| Method | What it does |
|---|---|
getCount() |
Total number of pages (same as document.getNumberOfPages()) |
get(int index) |
Page at that position (zero-based); same as document.getPage(i) |
indexOf(PDPage) |
Position of a page, or -1 if it isn't in the document |
iterator() / for (PDPage p : tree) |
Iterates over the pages in order |
add(PDPage) |
Adds at the end (same as document.addPage) |
insertBefore(newPage, next) |
Inserts newPage right before next |
insertAfter(newPage, previous) |
Inserts newPage right after previous |
remove(int index) / remove(PDPage) |
Removes the page from the tree (same as document.removePage) |
Important details:
- Indexes start at 0: the viewer's "page 1" is
get(0). insertBefore/insertAfterinsert the new page under the same parent node as the reference page, and update/Parentand every/Countup the tree. If the reference page doesn't belong to the document, they throwIllegalArgumentException.removetakes the page out of the tree, but doesn't destroy the object: you can add it again at another position. That's the basis for reordering.- With a full save, the objects of a removed page disappear from the file if nothing else uses them. With an incremental save, they're still present in the previous revision: removing a page doesn't erase the information (important if you're removing it for privacy reasons).
Adding, inserting and removing pages
Adding a blank page of the same size as the first one, at the beginning of the document, to use as a cover:
PDPage first = document.getPage(0);
PDPage cover = new PDPage(first.getMediaBox()); // same size
document.getPages().insertBefore(cover, first);new PDPage(PDRectangle) creates an empty page with that MediaBox. Once it's inserted, you draw on it as always with new PDPageContentStream(document, cover): it's a new page, so here the default OVERWRITE mode is correct.
Removing the second page:
When you remove several pages by index, each removal shifts the positions of the following ones. The classic solution is to remove them from the highest to the lowest index; you'll practise this in exercise 1.
Rotating pages
Rotating a page means changing its /Rotate entry with setRotation. As you saw in 02-01, it doesn't touch the content: it only tells the viewer how to display it. It's the ideal operation for fixing a page that was scanned sideways.
/** Rotates the page by the given degrees (multiple of 90, positive = clockwise). */
public static void rotate(PDPage page, int degrees) {
if (degrees % 90 != 0) {
throw new IllegalArgumentException("Rotation must be a multiple of 90: " + degrees);
}
int updated = ((page.getRotation() + degrees) % 360 + 360) % 360;
page.setRotation(updated);
}- The rotation is relative: it's added to the one the page already had. A page with
/Rotate 90rotated another 90 degrees ends up at 180. - The double-modulo formula normalises the result to 0, 90, 180 or 270, also with negative rotations (
rotate(page, -90)= 90 degrees anticlockwise). - If you then stamp something on that page,
Stamper(lesson 04-02) already takes/Rotateinto account so that the stamp comes out upright.
Reordering and moving pages
PDPageTree has no "move" method. You achieve it with the basic operations:
/**
* Reorders the document. order contains the (zero-based) indexes of the current pages in the
* desired order; each one must appear exactly once.
*/
public static void reorder(PDDocument document, int... order) {
PDPageTree tree = document.getPages();
int total = tree.getCount();
if (order.length != total || java.util.Arrays.stream(order).distinct().count() != total) {
throw new IllegalArgumentException("The order must include each page exactly once");
}
List<PDPage> current = new ArrayList<>();
tree.forEach(current::add); // 1) copy the references
for (PDPage page : current) { // 2) empty the tree
tree.remove(page);
}
for (int index : order) { // 3) add them back in the new order
tree.add(current.get(index));
}
}
/** Moves a page from position from to position to (zero-based indexes). */
public static void move(PDDocument document, int from, int to) {
PDPageTree tree = document.getPages();
PDPage page = tree.get(from);
tree.remove(page);
if (to >= tree.getCount()) {
tree.add(page);
} else {
tree.insertBefore(page, tree.get(to));
}
}How reorder works:
- Validation: the array must have as many elements as there are pages, with no repeats (
distinct().count()). That way no page is lost or duplicated by mistake. - Copying references: we store the
PDPageobjects in a Java list before touching the tree. You can't modify the tree while iterating over it. - Emptying and rebuilding: we remove every page and add them back in the requested order. The objects are the same: content, resources and annotations are preserved.
reorder(document, 1, 3, 0, 2) means: "the new first page is the old page 1, followed by 3, 0 and 2".
One side effect to keep in mind: add hangs every page from the root, so a tree with intermediate nodes gets flattened (the intermediate nodes left without pages remain in the tree, empty and with /Count 0). It's harmless for any viewer.
Duplicating a page within the same document
A real case: printing every invoice in duplicate, with the copy marked «CUSTOMER COPY». There's no need to generate it again: duplicating its pages is enough.
The most direct idea is to create a PDPage with a copy of the page dictionary. But that copy is shallow: the direct values it contains, such as the /Contents array, are the same Java object in the original and in the copy. Let's check this with the two-page invoice, whose /Contents is an array (the «Page X of N» footer was added with APPEND):
PDPage original = document.getPage(0);
PDPage copy = new PDPage(new COSDictionary(original.getCOSObject())); // naive copy
copy.getCOSObject().removeItem(COSName.PARENT);
document.getPages().insertAfter(copy, original);
new Stamper(document).watermark(copy, "COPY", false); // stamp ONLY the copy
// /Contents of the original: 5 elements; of the copy: 5 elements → the stamp is on both!PDPageContentStream with APPEND adds the new stream to the existing array, and that array is shared. The solution is to give the copy its own array, with the same references to the streams:
/**
* Duplicates a page within the same document and places the copy right after it.
* It shares streams and resources with the original, but has its own /Contents array,
* so you can stamp the copy without affecting the original.
*/
public static PDPage duplicate(PDDocument document, PDPage original) {
COSDictionary copyDict = new COSDictionary(original.getCOSObject()); // shallow copy
copyDict.removeItem(COSName.PARENT);
copyDict.removeItem(COSName.ANNOTS); // annotations point to their page: they aren't shared
COSBase content = copyDict.getDictionaryObject(COSName.CONTENTS);
if (content instanceof COSArray array) {
COSArray own = new COSArray();
for (int i = 0; i < array.size(); i++) {
own.add(array.get(i)); // same references to the streams, new array
}
copyDict.setItem(COSName.CONTENTS, own);
}
PDPage copy = new PDPage(copyDict);
document.getPages().insertAfter(copy, original);
return copy;
}new COSDictionary(other)copies the dictionary's entries: indirect references (12 0 R) point to the same objects and direct values are the same instances.- We remove
/ParentbecauseinsertAfterwill set the correct one. - We remove
/Annots: each annotation has a/Pentry pointing to its page, and sharing them between two pages confuses viewers. If the copy needs annotations, they would have to be cloned (lesson 06-05). array.get(i)returns the unresolved element (theCOSObjectreference), so the new array points to the same streams: the copy doesn't duplicate the data and the file barely grows.- If
/Contentsis a single stream (not an array), there's no problem:APPENDwill create a new array in the copy. - The resources (
/Resources) remain shared. That's harmless: ifStamperadds a font to the copy's resources, the original will simply have a font it doesn't use. - The "copy the container, share the content" pattern is what Java calls a defensive copy: you copy what you're going to modify.
Importing a page from another document: importPage and its problems
The legal department has prepared general-terms.pdf (in the example it's generated by GenerateGeneralTerms with TextBlock), and it has to be added at the end of invoices that have already been issued. PDDocument.importPage(PDPage) copies a page from another document and adds it at the end:
What it does internally (in PDFBox 3.0.x):
- It makes a shallow copy of the page dictionary, removes
/Parentand copies the content (/Contents) into a new stream of the target document. - It copies the MediaBox, the CropBox and the rotation.
- It doesn't copy the resources: the imported page still points to the fonts and images of the source document. They'll be copied to the target at the moment of saving.
That's where its problems come from:
| Problem | Consequence | Solution |
|---|---|---|
| Resources are read from the source document when saving | If you close the source before saving the target, the resulting file comes out corrupted (truncated streams, broken fonts), often without an exception | Keep the source open until after saving |
Inherited resources (defined on a /Pages node of the source) aren't imported |
The page comes out without fonts or images; PDFBox warns about it in the log (inherited resources of source document are not imported) |
imported.setResources(original.getResources()) |
| Annotations (links, fields) still point to pages of the source | The target may drag the entire source document along with it | Remove or rebuild the annotations (06-05) |
| Not for use with in-memory generated documents that haven't been saved | The documentation advises against it: they may have unfinished parts, such as pending font subsets | Save and reload the source, or import from a file |
The first problem clashes with our PdfEditor: saving happens after the lambda finishes. If you open the terms document inside the lambda with try-with-resources, it's closed before saving. We tested it: the result is generated without an exception, but when you load it warnings appear such as The end of the stream is out of range and Invalid ToUnicode CMap in font .... The correct way is to open the source outside:
try (PDDocument terms = Loader.loadPDF(new File("output/general-terms.pdf"))) {
PdfEditor.edit(invoice, target, PdfEditor.Mode.INCREMENTAL, document -> {
document.importPage(terms.getPage(0));
});
} // terms is closed AFTER the invoice has been savedTo combine entire documents, with their bookmarks, forms and structure, importPage falls short: in lesson 04-04 we'll use PDFMergerUtility, which deep-clones the objects. And in 04-05 you'll see LayerUtility.importPageAsForm, which imports a page as a reusable object.
Cropping with the CropBox
Cropping a page means changing its CropBox (lesson 02-01): the viewer only shows what lies inside it.
PDPage first = document.getPage(0);
PDRectangle media = first.getMediaBox();
// Show only the top half (header, issuer and customer)
first.setCropBox(new PDRectangle(0, media.getHeight() / 2, media.getWidth(), media.getHeight() / 2));new PDRectangle(x, y, width, height): here, from half the height up to the top.- Cropping is non-destructive: the content outside the CropBox is still in the file. Anyone can restore it, and
PDFTextStripper(lesson 06-01) still extracts that text. Never use the CropBox to hide confidential information; for that you have to remove the content (redaction), something much more complex. - When printing and rendering, most tools respect the CropBox. Watch out: some command-line utilities use the MediaBox by default (for example,
pdftoppmneeds the-cropboxoption).
Scaling a page: changing the MediaBox and transforming the content
Scaling is trickier than cropping: you have to change the paper size (MediaBox) and also transform the content so that it fits. Since the original content isn't touched, the transformation is placed before it with a PREPEND stream; and since that transformation must affect the original content, this time we do not close it in the same stream, but in an APPEND stream at the end.
flowchart LR
A["PREPEND stream:<br/>q 0.707 0 0 0.707 dx dy cm"] --> B["original content<br/>(untouched)"] --> C["APPEND stream:<br/>Q"]
/**
* Changes the size of the page and scales its content so that it fits, centred,
* keeping its proportions.
*/
public static void scale(PDDocument document, PDPage page, PDRectangle newSize) throws IOException {
PDRectangle current = page.getCropBox();
float factor = Math.min(newSize.getWidth() / current.getWidth(),
newSize.getHeight() / current.getHeight());
// Offset: move the visible corner to the origin, scale, and centre within the new size
float dx = (newSize.getWidth() - current.getWidth() * factor) / 2 - current.getLowerLeftX() * factor;
float dy = (newSize.getHeight() - current.getHeight() * factor) / 2 - current.getLowerLeftY() * factor;
// PREPEND: the transformation runs BEFORE the original content and affects it
try (PDPageContentStream before = new PDPageContentStream(document, page, AppendMode.PREPEND, true)) {
before.saveGraphicsState();
before.transform(new Matrix(factor, 0, 0, factor, dx, dy));
}
// APPEND without resetContext: closes the save we opened before the original content
try (PDPageContentStream after = new PDPageContentStream(document, page, AppendMode.APPEND, true, false)) {
after.restoreGraphicsState();
}
page.setMediaBox(new PDRectangle(newSize.getWidth(), newSize.getHeight()));
page.setCropBox(null); // with no CropBox, the visible area is the MediaBox again
page.setBleedBox(null);
page.setTrimBox(null);
page.setArtBox(null);
}Step by step:
- Scale factor: the minimum of the two ratios (width and height) guarantees that the whole page fits without distortion. From A4 to A5 it comes out at
0.707(A5 is A4 divided by √2). - Offset: first the CropBox corner (multiplied by the factor) is subtracted so that the visible area starts at
(0, 0); then half of the leftover space is added to centre it. - Why this is the only case in which we leave a
saveopen: in 04-02 the rule was that aPREPENDstream must leave the state clean. Here we want exactly the opposite: for the transformation to affect the original content. That's why we open it withsaveGraphicsState()in the stream in front and close it withrestoreGraphicsState()in the one behind, which is created withresetContext = false(if it weretrue, theQit adds at the beginning would close the first stream'sqtoo early, leaving the state unbalanced). - The boxes: the new MediaBox starts at
(0, 0); the other boxes are removed withnull, because their old coordinates no longer make sense. - Limitation: annotations and form fields have their own coordinates (
/Rect) that aren't transformed. An invoice has none; in a form you would have to recalculate them or useLayerUtility(04-05).
Typical use: a US supplier sends its delivery notes in letter size (PDRectangle.LETTER, 612 × 792 pt) and Nebula's archive is A4. scale(document, page, PDRectangle.A4) shrinks the content to 97.3% and centres it, leaving about 12.6 mm free at the top and bottom.
Blank pages for double-sided printing
When a batch of invoices is printed double-sided, an invoice with an odd number of pages makes the next one start on the back of the last sheet. The solution is to add a blank page when needed:
/** Adds a blank page at the end if the number of pages is odd (double-sided printing). */
public static boolean padForDuplex(PDDocument document) {
int total = document.getNumberOfPages();
if (total % 2 == 0) {
return false;
}
PDPage last = document.getPage(total - 1);
PDPage blank = new PDPage(last.getMediaBox()); // same size as the last one
document.addPage(blank);
return true;
}- We use the size of the last page so that the printer doesn't switch trays.
- The method returns whether it added the page, which is useful for reporting or for counting sheets.
- In official documentation it's customary to print "This page intentionally left blank" on that page; you can do that with
Stamper.stamp.
In lesson 04-04 we'll use this utility when merging the month's invoices into a single PDF.
The Pages utility and the example program
All the methods above (rotate, reorder, move, duplicate, scale, padForDuplex) make up the utility class com.invoicelab.editing.Pages (private constructor, static methods). The example program combines them with PdfEditor and Stamper:
package com.invoicelab.examples;
import com.invoicelab.editing.PdfEditor;
import com.invoicelab.editing.Stamper;
import com.invoicelab.editing.Pages;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
public class ManipulatePages {
public static void main(String[] args) throws IOException {
Path invoice = Path.of("output/F-2026-0001.pdf");
// 1) General terms at the end of the issued invoice (+ a blank sheet if the count is odd)
try (PDDocument terms = Loader.loadPDF(new File("output/general-terms.pdf"))) {
PdfEditor.edit(invoice, Path.of("output/F-2026-0001-with-terms.pdf"), PdfEditor.Mode.INCREMENTAL,
document -> {
document.importPage(terms.getPage(0));
boolean added = Pages.padForDuplex(document);
System.out.println("Pages: " + document.getNumberOfPages()
+ (added ? " (with blank sheet)" : ""));
});
} // terms is closed AFTER the invoice has been saved
// 2) Original + customer copy, interleaved
PdfEditor.edit(invoice, Path.of("output/F-2026-0001-original-and-copy.pdf"), PdfEditor.Mode.FULL,
document -> {
Stamper stamper = new Stamper(document);
int total = document.getNumberOfPages();
for (int i = 0; i < total; i++) {
PDPage original = document.getPage(i * 2); // copies already inserted shift the indexes
PDPage copy = Pages.duplicate(document, original);
stamper.watermark(copy, "CUSTOMER COPY", false);
}
System.out.println("Original and copy: " + document.getNumberOfPages() + " pages");
});
// 3) Reorder: copies first
PdfEditor.edit(Path.of("output/F-2026-0001-original-and-copy.pdf"),
Path.of("output/F-2026-0001-copies-first.pdf"), PdfEditor.Mode.FULL,
document -> Pages.reorder(document, 1, 3, 0, 2));
// 4) Rotate, crop and scale
PdfEditor.edit(invoice, Path.of("output/F-2026-0001-transformed.pdf"), PdfEditor.Mode.FULL,
document -> {
Pages.rotate(document.getPage(1), 90);
PDPage first = document.getPage(0);
PDRectangle media = first.getMediaBox();
// Show only the top half (header, issuer and customer)
first.setCropBox(new PDRectangle(0, media.getHeight() / 2, media.getWidth(), media.getHeight() / 2));
});
PdfEditor.edit(invoice, Path.of("output/F-2026-0001-A5.pdf"), PdfEditor.Mode.FULL,
document -> {
for (PDPage page : document.getPages()) {
Pages.scale(document, page, PDRectangle.A5);
}
});
}
}Observations:
- Block 1: the invoice (2 pages) plus the terms (1) add up to 3, so
padForDuplexadds a fourth, blank one. It's saved incrementally: the issued invoice remains intact inside the file. - Block 2:
watermark(PDPage, String, boolean)is the single-page version of the watermark from 04-02 (the version without a page walks through all of them calling this one). Thei * 2index compensates for the fact that each inserted copy shifts the following pages: after duplicating page 0, the old page 1 is at position 2. Only the copies carry «CUSTOMER COPY». - Block 3: with the order
1, 3, 0, 2the two copies move in front of the two originals. - Block 4: page 2 is displayed in landscape and page 1 shows only its top half; in the A5 file both pages measure 148 × 210 mm, with the content shrunk and centred.
Common Mistakes and Tips
- Removing several pages by index in ascending order. After deleting page 1, the old page 3 becomes page 2 and you delete the wrong one. Sort the indexes and remove from highest to lowest.
- Modifying the tree while iterating over it.
for (PDPage p : document.getPages()) document.removePage(p)fails or skips pages. Copy the references into a list first. - Duplicating with a naive shallow copy. The shared
/Contentsarray makes a stamp on the copy appear on the original too. UsePages.duplicate. - Closing the source document before saving after
importPage. The result may come out corrupted without any exception. Open the source outsidePdfEditor.edit. - Relying on the CropBox to hide data. The cropped content is still in the file and can be extracted.
- Forgetting the boxes when scaling. If you keep an old CropBox after changing the MediaBox, the viewer will show the wrong portion.
- Tip: after manipulating pages of third-party documents, check the result with
PdfInfo.printSummary(lesson 01-04) and open it in a viewer: number of pages, sizes and rotations should all be as expected.
Exercises
Exercise 1. Write static void removePages(PDDocument document, int... indexes), which removes the given pages (zero-based) even if they arrive unsorted or repeated. Try it by removing pages 4 and 2 (in viewer numbering) from F-2026-0001-with-terms.pdf.
Exercise 2. Insert a cover page at the beginning of F-2026-0001 with the title «ORDER DOCUMENTATION» centred, in 22 pt bold and corporate blue. Check with indexOf that the old first page is now at position 1.
Exercise 3. Create a one-page test PDF in letter size (PDRectangle.LETTER) with a red rectangle running along the edge, and convert it to A4 with Pages.scale. What scale factor is applied, and how much space is left at the top and bottom?
Solutions
Solution 1.
public static void removePages(PDDocument document, int... indexes) {
int[] sorted = Arrays.stream(indexes).distinct().sorted().toArray();
for (int i = sorted.length - 1; i >= 0; i--) { // from highest to lowest
document.removePage(sorted[i]);
}
}
// Viewer pages 4 and 2 = indexes 3 and 1
PdfEditor.edit(Path.of("output/F-2026-0001-with-terms.pdf"), Path.of("output/without-pages.pdf"),
PdfEditor.Mode.FULL, document -> {
removePages(document, 3, 1);
System.out.println(document.getNumberOfPages()); // 2
});distinct() avoids trying to delete the same position twice (which would remove a different page) and sorted() lets you iterate from highest to lowest. What remains is the first page of the invoice and the terms. If an index doesn't exist, removePage throws an exception: in production code, first validate that all of them lie between 0 and getNumberOfPages() - 1.
Solution 2.
PdfEditor.edit(Path.of("output/F-2026-0001.pdf"), Path.of("output/F-2026-0001-cover.pdf"),
PdfEditor.Mode.FULL, document -> {
PDPage first = document.getPage(0);
PDPage cover = new PDPage(first.getMediaBox());
document.getPages().insertBefore(cover, first);
InvoiceLabFonts fonts = new InvoiceLabFonts(document);
try (PDPageContentStream content = new PDPageContentStream(document, cover)) {
content.setNonStrokingColor(NebulaColors.BLUE);
TextMetrics.writeAligned(content, fonts.bold(), 22, "ORDER DOCUMENTATION",
cover.getMediaBox().getWidth() / 2, cover.getMediaBox().getHeight() / 2,
Alignment.CENTER);
}
System.out.println(document.getPages().indexOf(first)); // 1
});Here the short PDPageContentStream constructor is correct because the cover is a new page with no content. Accented characters such as «Ó» would also render correctly because DejaVu Sans is Unicode (lesson 02-03); a standard WinAnsi font would handle them too, but not other alphabets.
Solution 3.
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.LETTER);
document.addPage(page);
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
content.addRect(0, 0, 612, 792);
content.setStrokingColor(Color.RED);
content.setLineWidth(10);
content.stroke();
}
document.save("output/letter.pdf");
}
PdfEditor.edit(Path.of("output/letter.pdf"), Path.of("output/letter-a4.pdf"), PdfEditor.Mode.FULL,
document -> {
for (PDPage page : document.getPages()) {
Pages.scale(document, page, PDRectangle.A4);
}
System.out.println(document.getPage(0).getMediaBox()); // [0.0,0.0,595.27563,841.8898]
});The scale factor is min(595.28 / 612, 841.89 / 792) = min(0.9727, 1.063) = 0.9727: the width decides, because A4 is narrower than letter. The scaled content measures 595.28 × 770.4 pt, so 71.5 pt of height are left over, split into about 35.7 pt (12.6 mm) at the top and at the bottom. When you open letter-a4.pdf you'll see the red frame touching the sides, with white strips at the top and bottom.
Conclusion
You now have a firm grip on a document's page structure: PDPageTree gives you ordered access to a tree that may have intermediate nodes, and with add, insertBefore, insertAfter, remove and indexOf you can insert, remove, move and reorder. You know how to rotate with setRotation, crop with the CropBox (without forgetting that it doesn't hide data) and scale by changing the MediaBox and wrapping the original content in a transformation with PREPEND/APPEND. You've seen two real pitfalls: the shallow copy that shares the /Contents array, and the importPage whose source is closed before saving. The Pages utility gathers all these operations together.
importPage is fine for adding a single page, but it falls short for combining complete documents. In the next lesson we'll use PDFMergerUtility to merge all the month's invoices into a single batch PDF with a cover page, and Splitter to split documents by number of pages, by size or by the separator sheets of a scanned batch.
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
