2011-03-02 69 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 */} 

}