How to resize existing pdf page size
java, pdf
Solution
Using iText you can do something like this:
float width = 8.5f * 72;
float height = 11f * 72;
float tolerance = 1f;
PdfReader reader = new PdfReader("source.pdf");
for (int i = 1; i <= reader.getNumberOfPages(); i++)
{
Rectangle cropBox = reader.getCropBox(i);
float widthToAdd = width - cropBox.getWidth();
float heightToAdd = height - cropBox.getHeight();
if (Math.abs(widthToAdd) > tolerance || Math.abs(heightToAdd) > tolerance)
{
float[] newBoxValues = new float[] {
cropBox.getLeft() - widthToAdd / 2,
cropBox.getBottom() - heightToAdd / 2,
cropBox.getRight() + widthToAdd / 2,
cropBox.getTop() + heightToAdd / 2
};
PdfArray newBox = new PdfArray(newBoxValues);
PdfDictionary pageDict = reader.getPageN(i);
pageDict.put(PdfName.CROPBOX, newBox);
pageDict.put(PdfName.MEDIABOX, newBox);
}
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("target.pdf"));
stamper.close();
I introduced the tolerance because you likely don't want to change pages whose size is just a tiny fraction off.
Furthermore you might want to also count in the UserUnit value of the page even though it hardly ever is used.
Any general purpose PDF library is likely to allow something like this, either by providing an explicit method for resizing or by allowing direct access as used here.
Concerning your requirement free version you clarified in a comment free means without buy; you can use iText without buying some license as long as you comply with the AGPL.
Problem
In an application, user can upload any pdf file and which has dimensions of 8.46" x 10.97". As per our application dimensions should be 8.5" x 11". Question is, How to re-size the existing pdf page size to set 8.5" x 11"? I have to fix by code, not manually or commend line or external software. Please let me know which java supporting jar (free version) providing functionality to achieve this or through simple java fix also fine.