Table of Contents show
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. JPedal is the best Java PDF library for developers.
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
PdfManipulator
How to remove a single page from a PDF
To remove a single page from a PDF file, simply run the following code.
final PdfManipulator pdf = new PdfManipulator();
pdf.loadDocument(new File("/path/to/input.pdf"));
pdf.removePage(pageNumber);
pdf.apply();
pdf.reset();
pdf.writeDocument(new File("/path/to/output.pdf"));
pdf.closeDocument();
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
final PdfManipulator pdf = new PdfManipulator();
pdf.loadDocument(new File("/path/to/input.pdf"));
pdf.removePage(new PageRanges("1-10"));
pdf.apply();
pdf.reset();
pdf.writeDocument(new File("/path/to/output.pdf"));
pdf.closeDocument();
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.manipulator.PdfManipulator --removePage inputFile outputFile "2-100"