Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsSome links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
To export selected pages from a generated PDF in Java, open the completed source document, copy or extract the pages you want into a new PDF, then save and close the destination. For one continuous range, Apache PDFBox’s PageExtractor is direct; for non-contiguous selections, use a page-selection API such as iText 5’s PdfReader.selectPages, or copy individual pages with an API suited to your library and verify the document features you need to preserve.
Choose the method that matches the selection
| Need | Suitable method | Important detail |
|---|---|---|
| One continuous range, such as pages 5–10 | PDFBox PageExtractor or iText 7 copyPagesTo |
Page numbers are one-based; range endpoints are inclusive. |
| Scattered pages, such as 1, 3, and 7 | iText 5 PdfReader.selectPages, or a page-copy workflow |
Confirm the output order and check whether annotations, forms, and other document structures matter. |
| PDF created by your application moments ago | Finish and save it, reopen the saved file, then extract or copy | Importing from an unfinished generated document can encounter incomplete structures. |
If the project already uses PDFBox or iText, using that dependency is usually the least complicated path. Do not select a library solely from these snippets: check the version already in the build and the applicable license terms, especially for iText.
Extract a continuous page range with Apache PDFBox
PageExtractor takes a source PDDocument and a start and end page, then returns a new document containing the selected pages. PDFBox documents the endpoints as inclusive. Its API reference also documents that a start below 1 is clamped to page 1, an end beyond the source runs to its last page, and an invalid range can yield a blank document. Validate page numbers yourself rather than relying on those boundary behaviors.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →PDFBox 3.x example
This example uses PDFBox 3.x’s Loader.loadPDF. It assumes the input file exists, is readable, and is not encrypted with credentials the application has not supplied.
import java.io.IOException;
import java.nio.file.Path;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.multipdf.PageExtractor;
public class ExtractPdfRange {
public static void main(String[] args) throws IOException {
Path inputPath = Path.of("generated.pdf");
Path outputPath = Path.of("selected-pages.pdf");
int startPage = 5;
int endPage = 10;
try (PDDocument source = Loader.loadPDF(inputPath.toFile())) {
int pageCount = source.getNumberOfPages();
if (startPage < 1 || endPage < startPage || endPage > pageCount) {
throw new IllegalArgumentException(
"Expected 1 <= startPage <= endPage <= " + pageCount);
}
PageExtractor extractor =
new PageExtractor(source, startPage, endPage);
try (PDDocument selected = extractor.extract()) {
selected.save(outputPath.toFile());
}
}
}
}
For PDFBox 2.x, keep the extraction logic but use the 2.x loading API, such as PDDocument.load(inputPath.toFile()), and the imports available in the exact version in your build. Do not combine a 2.x dependency with 3.x-only classes or signatures. PDFBox’s 2.0 command-line documentation likewise describes one-based inclusive startPage and endPage selection; its example selects pages 5 through 10 of a 13-page source.
Validate before extracting
- PDF page indexes in these APIs start at 1. Java collections and arrays commonly start at 0, so convert deliberately when iterating.
- Require
startPage >= 1,endPage >= startPage, andendPage <= source.getNumberOfPages()if an invalid request should fail rather than produce a clamped or blank result. - Save to a different path from the input. Replacing the source while it is open can fail or risk damaging the input, depending on the filesystem and application flow.
- Use try-with-resources for both documents. Closing the selected document writes and finalizes the output; closing the source releases its resources.
Copy a continuous range with iText 7
For a project using iText 7, open the source with a reader, create a destination with a writer, and call copyPagesTo. The cited API is specifically iText 7.2.1. The method takes an inclusive page range and appends those pages to the destination document.
Rank #2
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import java.io.IOException;
import java.nio.file.Path;
public class CopyPdfRange {
public static void main(String[] args) throws IOException {
Path inputPath = Path.of("generated.pdf");
Path outputPath = Path.of("selected-pages.pdf");
int pageFrom = 5;
int pageTo = 10;
try (PdfDocument source = new PdfDocument(
new PdfReader(inputPath.toString()));
PdfDocument destination = new PdfDocument(
new PdfWriter(outputPath.toString()))) {
int pageCount = source.getNumberOfPages();
if (pageFrom < 1 || pageTo < pageFrom || pageTo > pageCount) {
throw new IllegalArgumentException(
"Expected 1 <= pageFrom <= pageTo <= " + pageCount);
}
source.copyPagesTo(pageFrom, pageTo, destination);
}
}
}
The destination is closed at the end of the try-with-resources block so its writer can finish the file. Check the terms for the iText distribution and version selected for your application; licensing depends on the distribution and how it is used.
Recommended Free Tools
Export non-contiguous pages
A range extractor is not a list selector: pages 1, 3, and 7 are three separate selections. In iText 5, PdfReader.selectPages accepts either a comma-separated range expression or a list of integer page numbers. The API documents that selection can reorder pages, but a page cannot be repeated.
iText 5 using page numbers
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import java.io.FileOutputStream;
import java.util.Arrays;
public class SelectPdfPages {
public static void main(String[] args) throws Exception {
String input = "generated.pdf";
String output = "selected-pages.pdf";
PdfReader reader = new PdfReader(input);
try {
reader.selectPages(Arrays.asList(1, 3, 7));
Document document = new Document();
try {
PdfCopy copy = new PdfCopy(document, new FileOutputStream(output));
document.open();
copy.addDocument(reader);
} finally {
document.close();
}
} finally {
reader.close();
}
}
}
Alternatively, call reader.selectPages("1,3,7") before copying. Use the list form when the selection is built programmatically. Validate each requested number against reader.getNumberOfPages() before selection, and reject duplicates if duplicates are not meaningful to your application. The selected order is the order represented by the selection, not necessarily the original document order.
This iText 5 sample uses the classic Document/PdfCopy API. Do not paste it into an iText 7 project: their document and page-copy APIs differ. Confirm the dependency version and applicable terms before choosing this route.
Rank #4
Extract from a PDF your application has just generated
When possible, separate document generation from extraction. Finish generation, save and close the original document, reopen that serialized file as the source, extract pages, then close both source and destination. Apache PDFBox’s PDDocument documentation warns that importing a page from a generated document can encounter unfinished parts, including font-subsetting information. Reopening the completed file avoids treating an in-progress in-memory document as though it were fully serialized.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11- Complete all content generation, including fonts, images, annotations, and document-level structures.
- Save and close the generated source PDF.
- Open the saved file with the extraction library and validate the requested pages.
- Create and save the selected-pages PDF to a separate output path.
- Close both documents and inspect the output in a PDF viewer or automated validation step.
PDFBox also warns that annotations pointing to pages outside the target may make the destination document much larger. Page selection is not automatically a promise that every document-level feature will be retained exactly as desired. If fidelity is important, test the actual output with the structures your PDFs use.
Best Value
Check output fidelity and operational behavior
Features to verify
- Annotations and links: check that annotations on retained pages behave correctly, particularly links to pages that were not selected.
- Forms: verify field values, widgets, and form behavior; do not assume selecting pages preserves every form relationship.
- Outlines and metadata: inspect bookmarks, document information, and other metadata if users depend on them.
- Encryption and permissions: confirm the reader can open the source and the destination has the intended security settings. Do not assume source encryption settings transfer as required.
- External references: test links and references that leave the selected pages or point to external resources.
- Page order and count: reopen the output and verify its page count and order match the request.
Performance and reliability
There is no universal runtime or memory figure for extraction: the cost depends on file size, page content, embedded resources, and the chosen library and version. Measure with representative PDFs from your own workload before setting timeouts or memory limits. For batch work, close each source and destination promptly, write to unique temporary paths, and only publish or rename the output after the save has completed successfully. Keep the original available until the new file has passed validation.
Troubleshooting common failures
| Symptom | Likely cause | What to check or change |
|---|---|---|
| Blank output | Invalid or reversed range, or page numbers outside the source | Read the source page count and enforce one-based bounds before extraction. PDFBox documents that an invalid range can yield a blank document. |
| Wrong pages appear | Off-by-one conversion from a zero-based UI or collection | Convert once at the boundary: a user-facing page 1 maps to API page 1, while a Java list index 0 maps to page 1. |
| Output file is missing or incomplete | Destination was not closed, save failed, or the process stopped before serialization | Use try-with-resources, wait for the save/close operation to finish, and write to a new output path. |
| Class or method not found | Code and dependency major versions do not match | Check the Maven or Gradle dependency and imports. Use PDFBox 3.x’s Loader pattern only with a compatible PDFBox version; PDFBox 2.x uses its own loading API. Keep iText 5 and iText 7 examples separate. |
| Page content or document size is unexpected | Generated document was imported before completion, or retained annotations reference pages outside the selection | Save and close the generated source, reopen it, then extract. Inspect annotations and test with representative documents. |
| Some document features do not behave as before | Page copying did not preserve a feature as the application expects | Test forms, outlines, metadata, encryption, annotations, and external references explicitly; adjust the library workflow if those structures are essential. |
Or skip the browser setup
ScreenshotNeo is for capturing a webpage as an image or PDF, not for extracting selected pages from an existing PDF. If your actual task is to capture a web page as a PDF, its one-request API is an alternative to setting up browser automation; it does not replace the Java page-selection methods above. See the ScreenshotNeo website and API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
- It removes cookie/consent banners, newsletter popups, and chat widgets before capture; each cleanup step can be turned off.
- Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; the response includes
X-Page-VerdictandX-Billedheaders. - An MCP server provides
take_screenshot,get_page_info, andcapture_pdftools for Claude, Cursor, and other MCP clients. - The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.
Sign up for 1,000 free screenshots a month with no card.
Free tools Windows power users keep installed
One-click scans. No signup required.
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.

