我正在尝试从文件系统上的html文件中读取由phantomjs创建的pdf。我做了以下事情。
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 :(得分:0)
似乎问题是你正在尝试将参数作为单个String执行。您应该使用Runtime.exec(String[] comand)这样的内容:
String[] cmdArray = new String[]{phantomLocation,scriptLocation,inputFile,destinationFileString};
Process process = Runtime.getRuntime().exec(cmdArray);
process.waitFor();
希望这有帮助。