How to resize existing pdf page size [closed]

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.

Leave a Comment