0

I am running wkhtmltopdf from Java. I create a process but this one seems to be hanging, as it repeats again and again the the console, also in the Task Manager.

This is how I run wkhtmltopdf:

String command = applicationLocation + "wkhtmltopdf.exe -O Landscape " + reqURL + "?" + reqQuery + " c:/PDF/" + folderName + "/" + id + "/" + folderName + ".pdf";
Process p = Runtime.getRuntime().exec(command);

How can I "destroy" the process, after the job has been done?

This did not work for me, the process never stopped and the code never entered the while loop either:

ProcessBuilder pb = new ProcessBuilder(application, htmlFilePath, pdfFilePath);
Process process = pb.start();

BufferedReader errStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); 
System.out.println("read errstreamreader");
//not "process.getInputStream()" 

String line = null;

line = errStreamReader.readLine(); 
while(line != null) { 
    System.out.println(line); 
    line = errStreamReader.readLine(); 

    if(line.equals("Done")) {
        process.destroy();
        System.out.println("destroyed process");
    }
} 
nimrod
  • 5,595
  • 29
  • 85
  • 149

2 Answers2

0

That was a very ugly problem. My code caused the loop. I called this class which generates the PDF from a servlet with this code:

// create pdf
if(action != null && action.equals("pdf")) {
    String reqURL = request.getRequestURL().toString();
    String reqQuery = "id=" + bomModuleId+ "&action=pdf";
    String folderName = "doonot";
    GeneratePDF obj = new GeneratePDF();
    obj.genrateCmd(reqURL, "xxx", "xxx", reqQuery, folderName, "10.07.2012");  
}

It turned out, that wkhtmltopdf used exactely the same URL, so it made a request to that page, landed in this loop, and called wkhtmltopdf again. So I ended up in like 450 wkhtmltopdf processes, and everything crashed.

Solution: I removed "&action=pdf"!

nimrod
  • 5,595
  • 29
  • 85
  • 149
0

As it turns out i had the same problem too: looping wkhtmltopdf creates a bunch of processes causing my machine,running Windows 7, to drastically slow down.

The problem isnt really with wkhtmltopdf as it is with Runtime exec. It creates more wkhtmltopdf processes without waiting for any of the previous to finish until the lack of the system's resources freezes your computer.

My Solution: add p.waitFor(). It will wait for the wkhtmltopdf process to finish and then continue the loop.

This solution can still be slow because now a large html file can slow down the completion of your loop. So, if you want a still faster solution I suggest using the --read-from-stdin option from wkhtmltopdf.

As for reading the output of wkhtmltopdf I suggest looking at this question and ALL of its answers.

Community
  • 1
  • 1