2014-07-03 103 views
0

我正在尝试从文件系统上的html文件读取由phantomjs创建的pdf。我做了以下。Runtime.getRuntime().exec()未按预期方式工作

 process = Runtime.getRuntime().exec(phantomLocation + scriptLocation + inputFile + " " + destinationFileString); 
     process.waitFor(); 

我指定phantomLocation,js脚本位置,inputHTML和destinationFileString(PDF要生成和提供服务)。

我正在写下面的servlet代码来读取生成的pdf并作为响应发送。

 InvokePhantom phantom = new InvokePhantom(inputHTMLFileName, destinationFile); 
     process.create();//call the above piece of code 
       //Set the response headers 
       response.setContentType("application/pdf"); 
       String headerKey = "Content-Disposition"; 
       String headerValue = String.format("attachment; filename=\"%s\"", attchmentName); 
       response.setHeader(headerKey, headerValue); 

       //For debugging 
       File file = new File(destinationFile); 
       System.out.println("destinationFile exists = " + file.exists()); 

       //Write to outputStream 
       fileInputStream = new FileInputStream(destinationFile); 
       outputStream = response.getOutputStream(); 
       byte[] buffer = new byte[1024]; 
       int bytesRead = -1; 
       while ((bytesRead = fileInputStream.read(buffer)) != -1) { 
        outputStream.write(buffer, 0, bytesRead); 
       } 
       outputStream.flush(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (writer != null) { 
        writer.close(); 
       } 
       if (outputStream != null) { 
        outputStream.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

但是由phantomjs生成的pdf文件不完整。当从命令行phantomjs运行正确创建PDF(从相同的HTML)。但是从java代码调用时,它不能正常工作。如何解决这个问题?

+0

您可以发布完整的命令,需要执行 – Sanjeev

+0

@Sanjeev phantomjs脚本? – phoenix

+0

由'phantomLocation + scriptLocation + inputFile +“”+ destinationFileString'创建的命令以及您在命令行上的执行方式 – Sanjeev

回答

0

看来问题在于你试图用参数作为单个字符串执行命令。你应该使用Runtime.exec(String[] comand)这样的事情:

String[] cmdArray = new String[]{phantomLocation,scriptLocation,inputFile,destinationFileString}; 
Process process = Runtime.getRuntime().exec(cmdArray); 
process.waitFor(); 

希望这会有所帮助。

+0

我正在获取退出值-1的变化 – phoenix

+0

尝试读取进程的错误流/输出流以获得更多信息 – Sanjeev