java - PDFWriter 中的 ByteArrayOutputStream 大小为零?

标签 java pdf itext pdf-generation

在过去的 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/

相关文章:

java - Java 中给定 key 的 AES 加密

java - Eclipse调试: Stack trace on event

java - 如何使 "provided"范围在 Android Studio 上工作?

c# - iTextSharp - 裁剪 PDF 文件 (C#)

pdf - pdfcopy返回空白pdf

java - Android list 配置出现问题

c++ - 使用 MFC 打印 PDF 文件

firebase - 是否可以在 SwiftUI 应用程序中显示 PDF 缩略图?

c# - 使用 ITextSharp 获取 PDF 中图像的位置(X、Y、宽度、高度)

java - 使用iText 7和Java生成pdf无法换行长英文单词