Sergio del Amo
Sergio del Amo

Reputation: 78096

How can I remove the first page of a PDF file with Java?

I was thinking about using a library such as PDFBox but I would like your input.

Upvotes: 0

Views: 3670

Answers (2)

Sergio del Amo
Sergio del Amo

Reputation: 78096

With IText

public void removeFirstPage(String input_filename, String output_filename) throws DocumentException, IOException {
    File outFile = new File(output_filename);
    PdfReader reader = new PdfReader(input_filename);
    int pages_number = reader.getNumberOfPages();
    if(pages_number > 0) {
        Document document = new Document(reader.getPageSizeWithRotation(1));
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(outFile));
        document.open();
    for(int i=2; i <= pages_number;i++) {
            PdfImportedPage page = copy.getImportedPage(reader, i);
        copy.addPage(page);
    }
        document.close();        
    }
}

Upvotes: 1

Martin Klinke
Martin Klinke

Reputation: 7332

I can recommend iText, it works pretty well for manipulating PDFs or even constructing them from scratch.

There is also a tutorial on how to manipulate PDFs. I didn't see a way to delete pages, but the tool supports creating a new PDF by copying content from another one. So you could just copy all the pages but the first.

Upvotes: 2

Related Questions