How can I crop the pages of an existing PDF document?

I have an existing document of which the pages are too big. How can I crop the pages?

30th October 2015
admin-marketing

Posted on StackOverflow on Apr 12, 2014 by choudhary

Take a look at the RotatePages example from my book. In the manipulatePdf() method, I loop over the pages, I take the page dictionary, and I change the /Rotate key to rotate the page. That's not what you need, but the principle is similar.

You need to get the /MediaBox and /CropBox value from the page dictionary:

PdfArray mediabox = pageDict.getAsArray(PdfName.MEDIABOX);
PdfArray cropbox = pageDict.getAsArray(PdfName.CROPBOX);

In many cases, cropbox will be null in which case you can safely ignore it and use the mediabox value instead.

The cropbox value (or if null, mediabox) is an array with 4 values. These values represent two coordinates: one for the lower-left corner of the page, the other one for the upper-right corner of the page. If you want to crop a page, you need to change these coordinates and either replace the existing cropbox value (if one already exists) or add a new cropbox value (if there is none).

pageDict.put(PdfName.CROPBOX, new PdfArray(new float[]{llx, lly, urx, ury}));

Where llx, lly are the x and y coordinate of the lower-left corner and urx, ury are the x and y coordinate of the upper-right corner.


Share this article

Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now