2017-05-29 11 views
0

私は過去1時間から私の頭を壊しています。私はこの問題を解決することができません...私はJavaで簡単にPDFを書くことができますが、私のoutputstreamサイズはゼロです...ここに私のコードです..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

最初のバイトは、ドキュメントを 'open()'すると書かれます。 'dsf'にバイトが含まれていないとのあなたの主張は間違っています。それは少なくともPDFファイルのヘッダ、 'PDF-1'などを含んでいます。もちろん、ファイルのサイズを見ると、それはちょうど12バイトなので0バイトのように見えるかもしれません。しかし、あなたが主張しているように** **ゼロではありません。 –

+0

ライターの行をSystem.out.printの前に置く – PSo

答えて

1

たぶん、あなたは、あなたがコンテンツにアクセスしようとすると、(document.close()writer.close()で)PDFを作成前を完了する必要があります

//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ファイルにはすべてのレコードが書かれています。乾杯:

関連する問題