Apache PDFBox is an open-source Java library for creating, reading, modifying, rendering, signing, and extracting content from PDF documents. It is useful when a Java application needs direct programmatic access to PDF files without relying on desktop software.
This PDFBox tutorial explains the library’s main components, Maven setup, common Java examples, licensing, limitations, and practical points to check when processing real documents.
What Apache PDFBox is used for
PDFBox provides Java APIs for working with the objects and content stored in a PDF. Common uses include:
- Creating PDF documents from Java
- Adding text, images, pages, and metadata
- Extracting text from existing PDF files
- Splitting, merging, or rearranging pages
- Rendering PDF pages as raster images
- Reading and completing AcroForm fields
- Encrypting and decrypting documents
- Applying or validating digital signatures
- Inspecting low-level PDF objects
- Using command-line utilities for selected PDF operations
PDFBox is maintained as an Apache Software Foundation project. Its source code, issue tracking, and release information are available through the official Apache PDFBox website and the Apache PDFBox GitHub repository.
PDFBox modules and Java APIs
| Component | Purpose |
|---|---|
PDDocument | Represents a PDF document and provides access to its pages and document-level settings. |
PDPage | Represents an individual page in a PDF document. |
PDPageContentStream | Writes text, images, and graphics to a page. |
PDFTextStripper | Extracts text from a loaded PDF document. |
PDFRenderer | Renders PDF pages to Java images. |
PDAcroForm | Provides access to interactive form fields. |
PDFMergerUtility | Combines multiple PDF documents. |
Splitter | Divides a PDF into separate documents. |
| Preflight | Checks PDF/A conformance when the corresponding module is included. |
| FontBox | Handles font data used by PDFBox. |
Add PDFBox to a Maven project
Add the PDFBox dependency to the project’s pom.xml. Replace the property value with the version selected for your application after checking the available PDFBox Maven releases.
<properties>
<pdfbox.version>YOUR_PDFBOX_VERSION</pdfbox.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>${pdfbox.version}</version>
</dependency>
</dependencies>
For a Gradle project, declare the same group, artifact, and chosen version:
implementation("org.apache.pdfbox:pdfbox:YOUR_PDFBOX_VERSION")
Use one consistent PDFBox release across related modules such as PDFBox, FontBox, Preflight, and XMPBox. Mixing incompatible module versions can cause runtime errors.
Create a PDF document with PDFBox
The following example creates a one-page PDF, writes a line of text, and saves the result as example.pdf.
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
public class CreatePdfExample {
public static void main(String[] args) throws IOException {
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage();
document.addPage(page);
try (PDPageContentStream content =
new PDPageContentStream(document, page)) {
content.beginText();
content.setFont(
new PDType1Font(Standard14Fonts.FontName.HELVETICA),
14
);
content.newLineAtOffset(72, 720);
content.showText("PDF created with Apache PDFBox");
content.endText();
}
document.save("example.pdf");
}
}
}
The try-with-resources statements close both the content stream and document even if an exception occurs. Closing resources is especially important in server applications that process many files.
Extract text from a PDF with PDFBox
Load the document and pass it to PDFTextStripper to obtain its extractable text.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class ExtractPdfText {
public static void main(String[] args) throws IOException {
File input = new File("input.pdf");
try (PDDocument document = Loader.loadPDF(input)) {
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
System.out.println(text);
}
}
}
Text extraction works when a PDF contains encoded text. A scanned document may contain only page images, so PDFBox alone cannot turn those images into words. Such documents require optical character recognition before or alongside text extraction.
The visual reading order of a page is not always the same as the order in which text operators are stored. Multi-column layouts, tables, unusual font encodings, and individually positioned characters can therefore require custom extraction logic.
Extract text from selected PDF pages
PDFTextStripper can limit extraction to a page range. Page numbers supplied to the stripper are one-based.
PDFTextStripper stripper = new PDFTextStripper();
stripper.setStartPage(2);
stripper.setEndPage(4);
String selectedPages = stripper.getText(document);
Render a PDF page as an image
PDFRenderer converts a page into a BufferedImage. PDF page indexes used by the renderer are zero-based, so index 0 refers to the first page.
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
public class RenderPdfPage {
public static void main(String[] args) throws Exception {
try (PDDocument document = Loader.loadPDF(new File("input.pdf"))) {
PDFRenderer renderer = new PDFRenderer(document);
BufferedImage image = renderer.renderImageWithDPI(
0,
150,
ImageType.RGB
);
ImageIO.write(image, "png", new File("page-1.png"));
}
}
}
A higher DPI produces a larger, more detailed image but also uses more memory. Applications that render large documents should process pages individually and release image references after use.
Merge PDF files with PDFBox
PDFMergerUtility provides a direct way to combine documents in a specified order.
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.io.MemoryUsageSetting;
PDFMergerUtility merger = new PDFMergerUtility();
merger.addSource("part-1.pdf");
merger.addSource("part-2.pdf");
merger.setDestinationFileName("combined.pdf");
merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
For large or untrusted files, review the memory-management options provided by the PDFBox version in use. Keeping every source document entirely in heap memory may not be suitable for a busy service.
PDFBox version compatibility
PDFBox code examples are not always interchangeable between major releases. For example, current APIs use Loader.loadPDF(...) for loading a file, while older tutorials may call a static loading method on PDDocument. Font construction and memory configuration APIs have also changed across releases.
- Check which major PDFBox release the example targets.
- Read the migration guide before upgrading an existing application.
- Keep related Apache PDFBox modules on compatible versions.
- Run tests against encrypted, malformed, scanned, and font-heavy sample files used by the application.
- Do not copy an older loading or font example into a newer project without checking the current API documentation.
PDFBox security and production considerations
- Close every document: Use try-with-resources so temporary resources and open streams are released.
- Limit input size: Reject files that exceed the application’s documented upload and processing limits.
- Control memory use: Rendering and merging high-resolution or page-heavy documents can consume substantial heap memory.
- Treat PDFs as untrusted input: Keep PDFBox and its dependencies maintained, and validate files before further processing.
- Handle encryption explicitly: A password-protected document may require credentials before its content can be accessed.
- Test embedded fonts: Text display and extraction depend on the fonts and character mappings available in the document.
- Use OCR where necessary: Image-only pages do not contain ordinary text for
PDFTextStripperto extract.
PDFBox and iText differences
PDFBox and iText are Java libraries that can create and modify PDFs, but their APIs, feature sets, support models, and licensing terms differ. PDFBox is distributed under the Apache License 2.0. iText editions may use different licensing arrangements, including open-source and commercial terms. A project should compare the exact version, required PDF features, deployment model, support needs, and applicable license before choosing either library.
PDFBox is often appropriate when a project needs an Apache-licensed Java library for general PDF manipulation. The decision should still be based on representative documents because complex layout generation, advanced signatures, form behavior, accessibility requirements, and archival compliance can require specialized testing or additional components.
Apache PDFBox tutorial QA checklist
- Confirm that every example targets the same PDFBox major release.
- Verify that created PDFs open correctly in more than one PDF viewer.
- Test text extraction with normal text PDFs, multi-column pages, embedded fonts, and scanned pages.
- Check whether page APIs use one-based page numbers or zero-based indexes.
- Confirm that every
PDDocumentand content stream is closed. - Measure heap use when rendering or merging the largest supported files.
- Test password-protected, damaged, and empty documents without exposing sensitive error details.
- Review the licenses of PDFBox and all other dependencies used by the application.
Apache PDFBox FAQs
What is Apache PDFBox used for?
Apache PDFBox is used by Java applications to create, read, modify, merge, split, render, sign, encrypt, and extract content from PDF documents.
Is PDFBox free for commercial use?
PDFBox is released under the Apache License 2.0, which permits commercial use subject to its conditions. Teams should retain required notices and review the license together with the licenses of any additional dependencies.
Can PDFBox extract text from a scanned PDF?
Not by itself when the scanned pages contain only images. PDFBox can extract embedded text and can render pages for processing, but converting text inside an image into characters requires an OCR engine.
Does PDFBox work with Android?
The standard PDFBox distribution targets Java environments and relies on APIs that are not all provided by Android. Android projects commonly evaluate an Android-compatible port, but compatibility, maintenance status, supported features, package size, and licensing should be checked before adoption.
Why does PDFBox text extraction return characters in the wrong order?
A PDF stores drawing instructions rather than a semantic document structure comparable to HTML. Text may be positioned character by character or stored in an order different from its visual reading order. Columns, tables, font encodings, and missing character maps can therefore affect extraction results.
TutorialKart.com