gpt4 book ai didi

java - PDFWriter 中的 ByteArrayOutputStream 大小为零?

转载 作者:行者123 更新时间:2023-12-02 02:48:14 25 4
gpt4 key购买 nike

在过去的 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();

NOTE:I am able to print map key values also but When i download PDF the size is zero.

最佳答案

也许您应该在尝试之前完成 PDF 创建(使用 document.close()writer.close())访问内容:

    //Finish writing the PDF
document.close();
writer.close();
//now check what's been written:
System.out.println("Size Of Byte Array is "+dsf.size());
ByteArrayInputStream bInput = new ByteArrayInputStream(dsf.toByteArray());
file = new DefaultStreamedContent(bInput, "pdf", fileName);

关于java - PDFWriter 中的 ByteArrayOutputStream 大小为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44235815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com