Skip to content

Instantly share code, notes, and snippets.

@orrjosh
Created November 10, 2017 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orrjosh/3e18233a032648594f041472b1b9fdf6 to your computer and use it in GitHub Desktop.
Save orrjosh/3e18233a032648594f041472b1b9fdf6 to your computer and use it in GitHub Desktop.
public File convert(final File file) throws IOException, UnsupportedFileException {
File convertedFile = null;
InputStream in = null;
try {
Dictionary<String, SaveOptions> availableConversions = getSaveOptions(file);
SaveOptions saveOptions = availableConversions.get("pdf");
if (saveOptions != null) {
in = new BufferedInputStream(new FileInputStream(file));
logger.debug("Starting conversion of: " + file.getName() + " to PDF");
saveOptions.setOutputType(OutputType.String);
String convertedFilePath = conversionHandler.convert(in, saveOptions);
convertedFile = new File(convertedFilePath);
} else {
logUnsupportedFileSaveOptions(availableConversions, file.getName());
throw new UnsupportedFileException("Unable to convert: \"" + file.getName() + "\", file not supported by groupdocs");
}
} catch (Exception e) {
if(e.getMessage().startsWith("Trying to load unknown file type")){
throw new UnsupportedFileException("Unable to convert: " + file.getName(), e);
}
throw e;
} finally {
if (in != null) {
IOUtils.closeQuietly(in);
}
}
return convertedFile;
}
private Dictionary<String, SaveOptions> getSaveOptions(final File file) throws FileNotFoundException, UnsupportedFileException {
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
return conversionHandler.getSaveOptions(in);
} catch (GroupDocsException e) {
throw new UnsupportedFileException("Unable to convert: \"" + file.getName() + "\", file not supported by groupdocs", e);
} finally {
if (in != null) {
IOUtils.closeQuietly(in);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment