2011-03-02 65 views
1

我有一個默認的Spring消息偵聽器正在運行。Spring JMS TextMessage寫入到PDF

當在onMessage擊中,它有作爲的TextMessage(NOT BytesMessage)

如何編寫成PDF文件?

我認爲有一些問題,下面我的代碼......所以將其寫入文件,但該PDF文檔無法打開......

if (message instanceof TextMessage) { 
     try { 
      //System.out.println(((TextMessage) message).getText()); 

      TextMessage txtMessage = (TextMessage)message; 
      ByteArrayInputStream bais = new ByteArrayInputStream(txtMessage.getText().getBytes("UTF8")); 

      String outStr=bais.toString(); 

      File newFile=new File("D:\\document.pdf"); 
      FileOutputStream fos = new FileOutputStream(newFile); 
      int data; 
      while((data=bais.read())!=-1) 
      { 
      char ch = (char)data; 
      fos.write(ch); 
      } 
      fos.flush(); 
      fos.close(); 

感謝您的任何建議

回答

1

請考慮使用pdf特定的API來創建/更新PDF文件。我強烈建議iText。一個pdf文件不僅僅是一個字節流。涉及到很多事情,你必須考慮字體,頁面大小,開始X和Y座標,文本的方向,添加新的頁面,Tabulat結構或自由風格和列表繼續。

網站上有很多代碼示例可幫助您入門。以下是使用iText API在pdf文件中添加文本的簡化片段:

try { 
    ... 

    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pdfFile)); 

    ... 

    PdfReader reader = new PdfReader(bis); 

    /* outs could be any output stream */ 

    stamper = new PdfStamper(reader,outs); 

    ... /* removed the code to get current page */ 

    PdfContentByte over = stamper.getOverContent(currentPage); 
    over.beginText(); 
    over.setFontAndSize(myFont, myFontSize); 
    over.setTextMatrix(xPoint, yPoint); 
    over.showText("Add this text"); 
    over.endText(); 
    ... /* removed code to adjust x and y coordinate and add page if needed */ 
} catch (Exception ex) { 
    ex.printStackTrace(); 
} finally { 
    try { 
     stamper.close(); 
    } catch (Exception ex) {/* handle exception */} 

    try { 
     outs.flush(); 
     outs.close(); 
    } catch (Exception ignored) {/* handle exception */} 

}