How can I crop the pages of an existing PDF document?
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.