【发布时间】:2017-05-29 06:21:57
【问题描述】:
从过去 1 小时开始,我一直在头疼,我无法解决这个问题...我知道用 java 编写 PDF 很容易,但我的输出流大小为零,...这是我的代码..
Document document = new Document();
try
{
ByteArrayOutputStream dsf = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, dsf);
document.open();
document.add(new Paragraph("Some content here"));
// Set attributes here
document.addAuthor("Lokesh Gupta");
document.addCreationDate();
document.addCreator("HowToDoInJava.com");
document.addTitle("Set Attribute Example");
document.addSubject("An example to show how attributes can be added to pdf files.");
if (frontPageMap != null && !frontPageMap.isEmpty()) {
PdfPTable table = new PdfPTable(frontPageMap.size()); // creating
// columns.
table.setWidthPercentage(100); // Width 100%
table.setSpacingBefore(10f); // Space before table
table.setSpacingAfter(10f); // Space after table
for (Map.Entry<String, Object> entry : frontPageMap.entrySet()) {
PdfPCell tempCell = new PdfPCell(new Paragraph(entry.getKey()));
tempCell.setBorderColor(BaseColor.BLUE);
tempCell.setPaddingLeft(10);
tempCell.setHorizontalAlignment(Element.ALIGN_CENTER);
tempCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(tempCell);
}
document.add(table);
}
System.out.println("Size Of Byte Array is "+dsf.size());
ByteArrayInputStream bInput = new ByteArrayInputStream(dsf.toByteArray());
file = new DefaultStreamedContent(bInput, "pdf", fileName);
document.close();
writer.close();
注意:我也可以打印地图键值,但是当我下载 PDF 时,大小为零。
【问题讨论】:
-
当您
close()文档时,会写入 PDF 的最后一个字节。当我查看您的代码时,我发现您忽略了这一点;您尝试在 关闭文档之前对字节数组执行某些操作。这是错误的,原因很明显。 -
当您
open()文档时写入第一个字节。您关于dsf不包含任何字节的指控是错误的。它至少包含一个 PDF 文件的标题:PDF-1.等等。当然,如果您查看文件的大小,它可能看起来好像是 0 字节,因为它只有十几个字节。但它不是您声称的为零。 -
把 writer 行放到 System.out.print 之前
-
@PSo 非常感谢
标签: java pdf itext pdf-generation