如何将现有A4 PDF文档转换为A3小册子? [英] How to convert an existing A4 PDF document to an A3 booklet?

查看:2558
本文介绍了如何将现有A4 PDF文档转换为A3小册子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我们需要在Java中将现有的A4尺寸pdf转换为A3尺寸PDF。由于我是itext api转换pdfs的新手,任何人都可以指导我如何在java中使用itext或任何其他api来做。如果提供样本参考,那么可以理解。

Hi We have a requirement to convert an existing A4 size pdf to A3 Size PDF in java. Since i am new to itext api conversion pdfs, Can anyone guide me how to do in java using itext or any other api to do. If sample reference provided then appreciable.

UPDATe:输出PDF应该是A3小册子格式。

UPDATe: Output PDF should be in A3 booklet format.

推荐答案

请看一下 MakeA3Booklet 示例。
在这个例子中,我们采用一个包含299张A4页面的现有PDF文档( primes.pdf )我们将其转换为150页的A3小册子( a3_booklet.pdf ):

Please take a look at the MakeA3Booklet example. In this example, we take an existing PDF document with 299 A4 pages (primes.pdf) and we convert it to a 150-page A3 booklet (a3_booklet.pdf):

public void manipulatePdf(String src, String dest)
    throws IOException, DocumentException {
    // Creating a reader
    PdfReader reader = new PdfReader(src);
    // step 1
    Document document = new Document(PageSize.A3.rotate());
    // step 2
    PdfWriter writer
        = PdfWriter.getInstance(document, new FileOutputStream(dest));
    // step 3
    document.open();
    // step 4
    PdfContentByte canvas = writer.getDirectContent();
    float a4_width = PageSize.A4.getWidth();
    int n = reader.getNumberOfPages();
    int p = 0;
    PdfImportedPage page;
    while (p++ < n) {
        page = writer.getImportedPage(reader, p);
        if (p % 2 == 1) {
            canvas.addTemplate(page, 0, 0);
        }
        else {
            canvas.addTemplate(page, a4_width, 0);
            document.newPage();
        }
    }
    // step 5
    document.close();
    reader.close();
}

我们创建凭证对象与 PageSize.A3 作为参数,但由于 PageSize.A3 是纵向的,我们将其旋转以便我们获取横向页面大小。我们需要A4页面的宽度(横向格式为A3页面宽度的一半),我们遍历现有文档中的所有页面。

We create a Document object with PageSize.A3 as parameter, but as PageSize.A3 is in portrait, we rotate it so that we get the page size in landscape. We need the width of the A4 page (which is half of the width of the A3 page in landscape format) and we loop over all the pages in the existing document.

如果我们遇到奇数页面,我们将其添加到位置(x = 0; y = 0)。如果我们遇到偶数页面,我们将其添加到(x = a4_width; y = 0)的位置,然后我们创建一个新页面。

If we encounter an odd page, we add it at position (x = 0; y = 0). If we encounter an even page, we add it at position (x = a4_width; y = 0) and we create a new page.

这篇关于如何将现有A4 PDF文档转换为A3小册子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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