Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

java - How to convert an existing A4 PDF document to an A3 booklet?

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: Output PDF should be in A3 booklet format.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...