【问题标题】:iText rotate() won't orient the first pageiText rotate() 不会定位第一页
【发布时间】:2012-07-05 17:13:53
【问题描述】:

我所阅读的有关 iText 的所有内容都表明您应该能够设置页面大小,然后创建一个新页面。但是由于某种原因,当我尝试这样做时,我的第一页没有旋转。但我的第二个是。有什么想法吗?

response.setContentType("application/pdf");
Document document = new Document();

try{
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, buffer); 
    document.open();
    //Start a new page
    document.setPageSize(PageSize.LETTER.rotate()); //  11" x 8.5"  new Rectangle(792f, 612f)

    document.newPage();
    Paragraph topText = new Paragraph();
    // add some content here...
    document.close(); 

    DataOutput dataOutput = new DataOutputStream(response.getOutputStream());
    byte[] bytes = buffer.toByteArray();
    response.setContentLength(bytes.length);

    for(int i = 0; i < bytes.length; i++) {
        dataOutput.writeByte(bytes[i]);
    }

} catch (DocumentException e) {
    e.printStackTrace();
}

【问题讨论】:

  • 尝试设置页面大小之前调用document.open()。 IIRC,document.newPage() 真正的意思是“完成当前页面,然后开始一个新页面”,即打开一个文档,其中一个空白页面可供使用。
  • 完美。感谢您的帮助。
  • 如果它有效,我会发布它作为答案。
  • 另外:你为什么要使用DataOutputStream逐字节写出PDF?如果是动态生成的,不如直接写到 HTTP 响应输出流;或者如果你真的想宣传内容长度,只需用OutputStream.write()写出字节数组@
  • PdfWriter.getInstance(document, response.getOutputStream()); 代替你现在拥有的,去掉DataOutputStream 和ByteArrayOutputStream。

标签: java itext


【解决方案1】:

document.newPage() 真正的意思是“完成当前页面并打开一个新页面”。这意味着在您open() 一个文档之后,您已经准备好一个空白页面(无论文档之前设置的大小)。

您应该在打开文档之前设置页面大小:

document.setPageSize(PageSize.LETTER.rotate());
document.open();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多