如何调整现有pdf页面大小

问题描述:

在应用程序中,用户可以上传任何尺寸为8.46x 10.97的pdf文件。根据我们的应用,尺寸应为8.5x 11。问题是,如何重新调整现有pdf页面大小以设置8.5x 11?我必须通过代码修复,而不是手动或推荐线或外部软件。请让我知道哪个java支持jar(免费版)提供实现此功能或通过简单的java修复也很好。

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.

使用iText你可以这样做:

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.

此外,您可能还希望计算页面的 UserUnit 值,即使它几乎没有使用过。

Furthermore you might want to also count in the UserUnit value of the page even though it hardly ever is used.

任何通用PDF库都可能允许这样的内容,或者提供一个显式的调整大小的方法,或允许直接访问这里使用的。

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.

关于您的要求免费版您在评论中明确了免费意味着没有购买;只要您遵守AGPL,就可以在不购买许可的情况下使用iText。

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.