如何调整现有的pdf页面大小 [英] How to resize existing pdf page size

查看:35
本文介绍了如何调整现有的pdf页面大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在应用程序中,用户可以上传任何尺寸为 8.46" x 10.97" 的 pdf 文件.根据我们的应用程序尺寸应为 8.5" x 11".问题是,如何将现有的 pdf 页面大小重新调整为 8.5" x 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.

这篇关于如何调整现有的pdf页面大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆