Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clip and create new pdf from existing pdf with page numbers as input - pdfbox

Tags:

java

pdf

pdfbox

I have a pdf file with 10 pages, I need to clip the pages from 2 to 5 and create a new pdf. What I am doing is like the following:

PDDocument pddDocument=PDDocument.load(new File("sample.pdf")); 
PDFTextStripper textStripper=new PDFTextStripper(); 
String text = textStripper.getText(pddDocument).toString();

I am simply reading the pdf file and writing into a new file. How can clip with upper and lower bound as page numbers? Please guide me?

like image 610
Santhucool Avatar asked Dec 10 '25 18:12

Santhucool


1 Answers

This solution (for PDFBox 1.8.*) creates a PDF file with the contents like you asked for. Note that pages are zero-based.

    File originalPdf = new File("{File Location}");
    PDDocument srcDoc = PDDocument.load(originalPdf);
    PDDocument dstDoc = new PDDocument();

    List<PDPage> srcPages = srcDoc.getDocumentCatalog().getAllPages();

    for (int p = 0; p < srcPages.size(); ++p)
    {
        if (p >= 1 && p <= 4)
            dstDoc.addPage(srcPages.get(p));
    }

    dstDoc.save(file2);
    dstDoc.close();
    srcDoc.close();

If you want to work from the command line instead, look here: https://pdfbox.apache.org/commandline/

Then use PDFSplit and PDFMerge.

like image 92
Tilman Hausherr Avatar answered Dec 13 '25 08:12

Tilman Hausherr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!