【发布时间】: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。