2017-05-29 31 views
0

我一直在打破我的頭從過去1小時我無法解決這個問題...我知道它很容易在Java中寫PDF,但我的輸出流大小爲零,...這是我的代碼..PDFWriter中的ByteArrayOutputStream大小爲零?

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大小爲零。

+1

當您關閉()文檔時,會寫入PDF的最終字節。當我查看你的代碼時,我發現你忽略了這一點;您在關閉文檔之前嘗試使用字節數組*。由於明顯的原因,這是錯誤的。 –

+1

當您打開()文檔時,會寫入第一個字節。你指稱'dsf'不包含任何字節是錯誤的。它至少包含PDF文件的標題:「PDF-1」等。當然,如果你看看文件的大小,那看起來好像是0字節,因爲它只有十幾個字節。但是,如你所說,它不是**零。 –

+0

把作家行放在System.out.print – PSo

回答

1

也許你應該完成創建的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); 
0
document.close(); 

writer.close(); 

ByteArrayInputStream bInput = new ByteArrayInputStream(dsf.toByteArray()); 

file = new DefaultStreamedContent(bInput, "pdf", fileName); 

System.out.println("Size Of Byte Array is "+dsf.size()); 

添加該代碼。在這裏你完成了PDF文件的寫作,然後你可以打印文件的大小。根據內容我的大小爲零,但生成的pdf文件應該包含所有記錄......乾杯:)