iText: Successfully resize one page pdf, but fail

2019-02-20 03:56发布

问题:

I need to resize every page in my pdf from letter to legal size. Here is what I got so far

 public void resize (float x, float y, float scale) throws Exception {
    PdfReader reader = new PdfReader(pdfIn);
    Document doc = new Document(PageSize.LEGAL, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(pdfOut));
    doc.open();
    PdfContentByte cb = writer.getDirectContent();
    for(int i=1; i<=reader.getNumberOfPages(); i++){
        PdfImportedPage page = writer.getImportedPage(reader, i);
        cb.addTemplate(page, scale, 0, 0, scale, x, y);
    }
    doc.close();
}

Even though the resize is correct, the output pdf only contain 1 page. Any help please?

回答1:

Here is the answer. I need doc.newPage() in the loop, read Marc B comment on my original question for more information

public void resize (float x, float y, float scale) throws Exception {
    PdfReader reader = new PdfReader(pdfIn);
    Document doc = new Document(PageSize.LEGAL, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(pdfOut));
    doc.open();
    PdfContentByte cb = writer.getDirectContent();
    for(int i=1; i<=reader.getNumberOfPages(); i++){
        doc.newPage();
        PdfImportedPage page = writer.getImportedPage(reader, i);
        cb.addTemplate(page, scale, 0, 0, scale, x, y);
    }
    doc.close();
}