wkhtmltopdf从java调用被绞死

时间:2017-08-15 23:57:36

标签: java pdf-generation wkhtmltopdf processbuilder

我们使用以下代码使用wkhtmltopdf生成PDF

    public class SystemUtils{   
    public String executeCommand(String... command) {
        Process process = null;
        try {
            // Using redirectErrorStream as true. Otherwise we have to read both process.getInputStream() and
            // process.getErrorStream() in order to not exhaust the stream buffer.
            process = new ProcessBuilder(command).redirectErrorStream(true).start();
            process.waitFor();

            StringBuilder outputBuilder = new StringBuilder();
            try(BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = stdError.readLine()) != null) {
                    outputBuilder.append(line).append(StringConstants.CARRIAGE_RETURN);
                }
            }
            return outputBuilder.toString();
        } catch (IOException | InterruptedException e) {
            String exceptionMsg = "Error while executing command '"+command+"' : ";
            LOGGER.error(exceptionMsg, e);
            throw new AppException(exceptionMsg, e);
        } finally {
            if(process != null){
                process.destroy();
            }
        }
    }

       public static void main(String[] args){
        SystemUtils systemUtils = new SystemUtils();
        String[] array = {"wkhtmltopdf", "/home/pgullapalli/Desktop/testsimilar1.html", "/home/pgullapalli/Desktop/test.pdf"};
        systemUtils.executeCommand(array);
    }
}

这适用于较小尺寸的文件。但是当我们尝试处理更大的文件时,它无限期地等待而没有任何响应。我不确定出了什么问题?有人可以建议吗?

1 个答案:

答案 0 :(得分:0)

我在return语句之前移动了process.waitFor()并且它开始工作了。这可能是因为输出缓冲区已经填满而我们没有从中读取。在流读取之后移动process.waitFor之后,一切正常。