The PDF file format is not natively supported by Java. Therefore, to remove a page from a PDF file, you will need an external library. This tutorial explains how to do this using JPedal.
Getting Started
- Add JPedal to your class or module path (download the trial jar)
- Create a File handle pointing to the PDF file
- Call one of the methods below from
PdfPageDeletion
How to remove a single page from a PDF
To remove a single page from a PDF file, simply call the following method.
PdfPageDeletion.deleteSinglePage(new File("/path/to/input.pdf"), new File("/path/to/output.pdf"), singlePageNumber;
How to remove pages in a range
To remove a range of pages from a PDF file, simply call the following method. Note that the range is inclusive.
PdfPageDeletion.deletePageRange(new File("/path/to/input.pdf"), new File("/path/to/output.pdf"), rangeStart, rangeEnd);
How to remove multiple pages in a custom range
To remove a pages in multiple different ranges, simply call the following method. The page range must be defined using SetOfIntegerSyntax
PdfPageDeletion.deletePageRange(new File("/path/to/input.pdf"), new File("/path/to/output.pdf"), stringPageRange);
How to remove pages using the command line
JPedal also allows you to remove pages from a PDF file through the command line
java -cp jpedal.jar org.jpedal.tools.PdfPageDeletion inputFile outputFile "2-100"
Before and After
The JPedal PDF library allows you to solve these problems in Java
Viewer viewer = new Viewer();
viewer.setupViewer();
viewer.executeCommand(ViewerCommands.OPENFILE, "pdfFile.pdf");
//Convenience static method (see class for additional options)
ExtractClippedImages.writeAllClippedImagesToDir("inputFileOrDirectory", "outputDir", "outputImageFormat", new String[] {"imageHeightAsFloat", "subDirectoryForHeight"});
//Convenience static method (see class for additional options)
ExtractTextAsWordList.writeAllWordlistsToDir("inputFileOrDirectory", "outputDir", -1);
//Convenience static method (see class for additional options)
ArrayList resultsForPages = FindTextInRectangle.findTextOnAllPages("/path/to/file.pdf", "textToFind");
PrintPdfPages print = new PrintPdfPages("C:/pdfs/mypdf.pdf");
if (print.openPDFFile()) {
print.printAllPages("Printer Name");
}
//Convenience static method (see class for additional options)
ExtractClippedImages.writeAllClippedImagesToDir("inputFileOrDirectory", "outputDir", "outputImageFormat", new String[] {"imageHeightAsFloat", "subDirectoryForHeight"});
Why do developers choose JPedal over alternatives?
- Actively developed commercial library with full support and no third party dependencies.
- Simple licensing options and source code access for OEM users.
- Process PDF files up to 3x faster than alternative Java PDF libraries.