Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Render repeating text at the page level, not in the document’s normal content flow. In iText 7, register START_PAGE and END_PAGE event handlers; in iText 5, use PdfPageEventHelper.onEndPage; with Apache PDFBox, append a PDPageContentStream to each page. Reserve top and bottom margins, calculate positions from each page’s geometry, and defer the total-page value when you need “Page X of Y.”
Choose the right implementation pattern
| Situation | Best fit | Why |
|---|---|---|
| Generating a new document with modern layout APIs | iText 7 page events | High-level layout, tables and canvas drawing can share one document model. |
| Maintaining an iText 5 application | PdfPageEventHelper |
Its page-event lifecycle is designed for repeated page decorations. |
| Adding marks to an existing PDF | Apache PDFBox append mode | You open the file, iterate pages and write directly onto each page. |
Headers and footers should be independent of body paragraphs. Adding them as ordinary paragraphs makes them flow only where inserted and can cause inconsistent placement when content reflows.
iText 7: page-level event handlers
Register a handler for PdfDocumentEvent.START_PAGE to draw a header and one for END_PAGE to draw a footer. The event receives the page, so coordinates can be derived from that page’s rectangle rather than hard-coded for one paper size.
Minimal new-document example
PdfWriter writer = new PdfWriter("out.pdf");
PdfDocument pdf = new PdfDocument(writer);
pdf.addEventHandler(PdfDocumentEvent.START_PAGE,
new Header("Company — Report"));
pdf.addEventHandler(PdfDocumentEvent.END_PAGE,
new Footer());
Document document = new Document(pdf);
// Add body content here.
document.close();
A handler normally creates a Canvas (or uses PdfCanvas for lower-level operations), selects a font and places text within the page rectangle. Keep the header inside the reserved top margin and the footer inside the reserved bottom margin.
#1 Best Overall
- EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
- READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
- CREATE, COMBINE, SCAN and COMPRESS PDFs
- FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
- LIFETIME License for 1 Windows PC or Laptop. 5GB MobiDrive Cloud Storage Included.
Reserve space before adding body content
Document document = new Document(pdf);
document.setMargins(60, 36, 54, 36); // top, right, bottom, left
The exact values depend on your type size, line height, logo and separator rule. The important rule is that the body’s layout area ends before the decoration begins; drawing a footer over an unmodified body margin does not change where paragraphs are laid out.
“Page X of Y” numbering
The current page number is available while an end-page event runs. The final page count may not yet exist, so write a placeholder for the total and fill it after all pages have been created. iText’s official HTML-to-PDF event example uses this deferred approach: reserve a PDF form field or placeholder, complete conversion, then replace it with the final count. Do not assume the total during the first page event.
HTML-to-PDF conversion
When using iText’s pdfHTML, attach the same start- and end-page handlers to the PdfDocument used by the converter. This keeps the repeating elements outside the HTML body while allowing the body to paginate normally.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstalliText 5: PdfPageEventHelper
For iText 5, subclass PdfPageEventHelper, override onEndPage, and register the instance with PdfWriter.setPageEvent. The callback runs when a page is finished. The API specifically cautions against calling Document.add() from a page event; draw through the writer’s canvas instead.
class HeaderFooter extends PdfPageEventHelper {
@Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte canvas = writer.getDirectContent();
ColumnText.showTextAligned(
canvas, Element.ALIGN_CENTER,
new Phrase("Report header"),
(document.left() + document.right()) / 2,
document.top() + 12, 0);
ColumnText.showTextAligned(
canvas, Element.ALIGN_CENTER,
new Phrase("Page " + writer.getPageNumber()),
(document.left() + document.right()) / 2,
document.bottom() - 12, 0);
}
}
Document document = new Document(PageSize.A4, 36, 36, 60, 54);
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("out.pdf"));
writer.setPageEvent(new HeaderFooter());
document.open();
// Add paragraphs, tables and images.
document.close();
Use writeSelectedRows when the header or footer is a table (for example, a logo at left and report title at right). Set the table width explicitly and place its baseline inside the margin. For different first-page artwork, inspect writer.getPageNumber() and branch carefully; do not create body elements from the callback.
Apache PDFBox: append content to every page
PDFBox is a direct fit for an existing file. Open or create the document, iterate through its pages, and append a PDPageContentStream. The append mode preserves existing page content while the reset-context flags help isolate graphics state from what was already on the page.
try (PDDocument doc = Loader.loadPDF(input.toFile())) {
PDFont font = new PDType1Font(FontName.HELVETICA);
int pageNo = 1;
for (PDPage page : doc.getPages()) {
PDRectangle box = page.getMediaBox();
try (PDPageContentStream cs = new PDPageContentStream(
doc, page, PDPageContentStream.AppendMode.APPEND,
true, true)) {
cs.beginText();
cs.setFont(font, 9);
cs.newLineAtOffset(36, box.getHeight() - 24);
cs.showText("Report header");
cs.endText();
}
pageNo++;
}
doc.save(output.toFile());
}
For a footer, use a y-coordinate near the lower edge, such as 24 points, while ensuring it remains inside the printable area. Add the page number with pageNo; a total requires knowing doc.getNumberOfPages() before the loop. Use a font that can encode every character in your text; standard Type 1 fonts are not sufficient for all Unicode scripts.
Recommended Free Tools
Rotation and page boxes
Pages can have different media boxes, crop boxes and rotations. A coordinate that is correct for an unrotated portrait page can put a header on the side of a landscape or rotated page. Read each page’s rotation, derive effective width and height, and transform the placement accordingly. If your input mixes orientations, test every orientation and avoid assuming one global page size.
Prevent overlap and clipping
- Reserve top and bottom margins before laying out body content.
- Measure the actual header and footer height, including logos, rules and wrapped titles.
- Place text relative to the page rectangle, not a constant coordinate copied from another paper size.
- Keep decorative drawing operations in the page callback; never insert normal body flow from that callback.
- For existing PDFs, inspect the crop box as well as the media box because viewers commonly display the crop box.
- Render a sample with long headings, large tables, images and the final page to verify that nothing touches the decoration.
Existing PDFs versus newly generated PDFs
When generating
Page events are deterministic: every page created by the layout engine receives the same callback. They are ideal for branding, chapter labels, dates and current-page numbers. If content can trigger a new page inside a handler, you risk recursion; handlers should only draw.
Rank #2
- Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.
- Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
- Read & Annotate. Enjoy intuitive reading modes and powerful tools to comment, highlight, and mark up PDFs.
- Create & Manage PDFs. Create new PDFs, combine multiple files, scan documents, and compress for easy sharing.
- Fill & Sign Forms. Complete forms and digitally sign documents with secure e-signature tools.
When modifying
PDFBox append mode (or an equivalent low-level iText operation) writes on top of existing page content. It does not reflow paragraphs or create additional margin. Choose coordinates that are empty in the source file, or deliberately place a translucent band behind the header and accept that it will cover content.
Custom content patterns
Titles and metadata
Draw a short title in the header and put detailed document metadata in the PDF catalog or document information dictionary. Long titles should be measured and wrapped or shortened; a single-line showText call will not wrap automatically.
Rules, logos and tables
Use canvas line operations for separator rules, an image object for a logo, and a fixed-width table when columns must align. Keep all three inside the reserved region and use the page’s left and right margins as the table boundaries.
Different first and last pages
Branch on the page number in the event. For a last-page variant, defer the decision until the total is known or run a second pass; an end-page callback on page one cannot know that it is the last page yet.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Troubleshooting
Header appears behind body text
The body margin is too small or the drawing order places the header beneath opaque content. Increase the top margin, move the header into the reserved band, or draw an opaque background intentionally.
Footer is cut off
The y-coordinate is outside the crop box, or the page is rotated. Use the page’s effective dimensions and keep the baseline plus font ascent inside the visible box.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Only the first page has a header
The code drew once after document creation instead of registering a page event or iterating every page. Register the handler before adding content, or place the PDFBox write operation inside the page loop.
“Page X of Y” shows a blank or wrong total
The total was evaluated before pagination finished. Use a deferred placeholder and fill it after closing/conversion, or perform a second pass once the page count is fixed.
Existing content disappears in PDFBox
The stream was opened in overwrite mode. Use PDPageContentStream.AppendMode.APPEND and close the stream for each page before saving.
Rank #3
- EVERY PDF TOOL UNLOCKED - 30+ tools in one app: edit text and images, convert, merge, split, compress, sign, OCR, redact, watermark, batch process, and more. No feature gates, no upsells, nothing held back.
- PAY ONCE, OWN FOREVER — A one-time purchase, not a subscription. Other apps runs $240/year — Scrivar is yours for life, with free updates included.
- UNLIMITED eSIGN, BUILT IN — Send contracts and forms for signature and track every step. Recipients sign in their browser with no account or app needed. Replace DocuSign and save hundreds a year.
- PC, MAC, AND WEB — Install on any Win 10/11 PC or macOS 11+ Mac (Intel or Apple Silicon), or work in your browser at scrivar.com. Same tools, same account, everywhere you work.
- OCR + FULL OFFICE CONVERSION — Turn scanned documents into searchable, selectable text, and convert PDFs to and from Word, Excel, and PowerPoint with formatting kept intact.
Characters are missing or garbled
The selected font lacks glyphs or the string is not encoded as expected. Embed a Unicode-capable font and verify the font licensing and embedding requirements for your deployment.
Handler causes an exception or runaway pagination
Do not call Document.add() from an iText page event. Draw directly with the event’s canvas and keep the callback side-effect free.
Performance, reliability and licensing
Header and footer drawing is usually small compared with image decoding, font embedding and HTML conversion. Reuse loaded fonts and logo resources, avoid opening a new font or image stream for every page, and close documents and content streams with try-with-resources where the API permits. For large existing PDFs, process pages sequentially and save only after all decorations are written.
Apache PDFBox is published under the Apache License 2.0. iText licensing depends on the edition and deployment; confirm the current terms for your application before shipping, especially when combining iText 7 with pdfHTML.
Or skip the browser setup
If your Java service only needs a clean image or PDF of a web page to place in a report, ScreenshotNeo provides a one-call API instead of maintaining a browser. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; bot checks, blank pages, failed loads, timeouts and cache hits are not billed, with the result identified by X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.
Free tools Windows power users keep installed
One-click scans. No signup required.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for PDF options, selectors, device presets, JavaScript, custom headers and asynchronous jobs. The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Frequently Asked Questions
Can I put a header only on odd or even pages?
Yes. In the page callback, inspect the current page number and return without drawing on pages that should remain blank.
Can a footer contain an image or a QR code?
Yes. Add the image as another drawing operation in the same reserved footer region, and calculate its dimensions before positioning adjacent text.
Will adding a footer change existing PDF text selection?
No. Appended drawing adds a new content stream; it does not reflow or rewrite the original text, although it can visually cover text if coordinates overlap.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesThe Bottom Line
Use page events for new iText documents, PdfPageEventHelper for iText 5, and PDFBox append mode for existing files. Geometry-aware coordinates and reserved margins are what keep custom headers and footers consistent and readable.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

