java iText:成功调整一页pdf的大小,但当pdf文档中有多个页面时失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7179096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:58:32  来源:igfitidea点击:

iText: Successfully resize one page pdf, but fail when there are multiple pages in the pdf document

javaresizeitext

提问by Thang Pham

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

我需要将 pdf 中的每一页从字母大小调整为合法大小。这是我到目前为止所得到的

 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?

即使调整大小正确,输出 pdf 也只包含 1 页。请问有什么帮助吗?

回答by Thang Pham

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

这是答案。我需要doc.newPage()在循环中,阅读Marc B对我的原始问题的评论以获取更多信息

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