2011-08-29 40 views
3

我需要一些幫助,這裏有我的PDF轉換器程序。Java:PDF轉換器可以在Mac中使用,但在Windows中可以生成空的PDF文件

所以,我正在使用JADE框架來做這個移動代理PDF轉換器。但是,我面臨的問題更多地與我將文本文件轉換爲PDF,將其作爲二進制文件在網絡上傳輸並將其恢復爲PDF文件的方式相關。

我寫的程序在我的MacBook上正常工作。 但是,在Windows上,它將我的PDF文件恢復爲空白PDF。

這是我用來發送PDF文件的代碼。

private void sendPDF(File f, String recipient) { 
    String content = ""; 

    if(f != null) { 
     try { 
      FileInputStream fis = new FileInputStream(f); 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

      int noBytesRead = 0; 
      byte[] buffer = new byte[1024]; 

      while((noBytesRead = fis.read(buffer)) != -1) { 
       baos.write(buffer, 0, noBytesRead); 
      } 

      content = baos.toString(); 
      fis.close(); 
      baos.close(); 

      System.out.println("Successful PDF-to-byte conversion."); 
     } catch (Exception e) { 
      System.out.println("Exception while converting PDF-to-byte."); 
      content = "failed"; 
      e.printStackTrace(); 
     } 
    } else { 
     System.out.println("PDF-to-file conversion failed."); 
     content = "failed"; 
    } 

    ACLMessage message = new ACLMessage(ACLMessage.INFORM); 
    message.addReceiver(new AID(recipient, AID.ISLOCALNAME)); 
    message.setContent(content); 

    myAgent.send(message); 
    System.out.println("PDF document has been sent to requesting client."); 
} 

而且,這裏是我用來恢復PDF的代碼。

private File restorePDF(String content) { 
    String dirPDF = dirBuffer + "/" + new Date().getTime() + ".pdf"; 
    File f = new File(dirPDF); 

    try { 
     if(!f.exists()) f.createNewFile(); 

     byte[] buffer = new byte[1024]; 
     ByteArrayInputStream bais = new ByteArrayInputStream(content.getBytes()); 
      FileOutputStream fos = new FileOutputStream(f); 

     int noBytesRead = 0; 
     while((noBytesRead = bais.read(buffer)) != -1) { 
       fos.write(buffer, 0, noBytesRead); 
    } 

     fos.flush(); 
     fos.close(); 
     bais.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     f = null; 
    } 

    return f; 
} 

對此的任何幫助將不勝感激! :)

+0

任何日誌?異常?跟蹤? – Snicolas

回答

0

一個問題是,你正在使用錯誤的分隔符字符。 Java有一個內置的函數,它將返回正確的字符爲正確的操作系統。見separator char

您的代碼將是這個樣子

String dirPDF = dirBuffer + File.separatorChar + new Date().getTime() + ".pdf"; 

參考:

separatorChar

與系統有關的默認名稱分隔符。此字段爲 已初始化爲包含系統 屬性file.separator值的第一個字符。 在UNIX系統上,此字段的值爲 '/';在Microsoft Windows系統上它是'\'。

1

問題有點令人困惑,因爲沒有關於PDF內容的具體內容。

我想你實際上是想發送字節,實際上是發送一個字符串,並且客戶端和服務器上的字符串編碼是不同的。

這通常就是麻煩發生:

content = baos.toString(); 

和:

content.getBytes() 
+0

我認爲就是這樣。結合閱讀PDF然後將其轉換爲字符串的事實看起來非常危險,即使兩端的編碼匹配。 @hsoetikno:你不能只寫字節嗎?如果沒有,也許使用BASE64或類似的東西。 – Thilo

1

一個PDF文件是查找表和大量的二進制數據塊的二進制文件格式,以使其成爲一個字符串打破它。如果你想了解一個PDF文件的內部,我已經寫了一大堆關於它的博客文章(http://www.jpedal.org/PDFblog/2010/09/understanding-the-pdf-file-format -series /)

相關問題