Last active
December 4, 2018 07:48
-
-
Save dlundy/ff2d0d0e29b041ef36e3 to your computer and use it in GitHub Desktop.
Quickie Java pipe out to wkhtmltopdf to create a pdf from a string with html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public byte[] getPdf(String html) { | |
byte[] results = null; | |
try { | |
// For piping in and out, we need separate args for this for some reason | |
String[] command = {"/usr/local/bin/wkhtmltopdf", "-", "-"}; | |
ProcessBuilder builder = new ProcessBuilder(command); | |
// this eats up stderr but prevents us from having to handle it ourselves | |
builder.redirectErrorStream(false); | |
Process process = builder.start(); | |
try (BufferedOutputStream stdin = new BufferedOutputStream(process.getOutputStream())) { | |
stdin.write(html.getBytes()); | |
} | |
try(BufferedInputStream stdout = new BufferedInputStream(process.getInputStream()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ) { | |
// Couldn't get a buffered read working properly without knowing the length of the result, so reading byte by byte instead. | |
// BufferedInputStream should be buffering internally with 8192 bytes, and | |
// ByteArrayOutputStream works similar to a vector with an internal byte array, so performance shouldn't be too bad. | |
// TODO: properly buffer this | |
while (true) { | |
int x = stdout.read(); | |
if (x == -1) { | |
break; | |
} | |
outputStream.write(x); | |
} | |
results = outputStream.toByteArray(); | |
process.waitFor(); | |
} | |
} | |
catch(Exception e) { | |
log.error("Exception thrown while converting to pdf: " + e); | |
return null; | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment