private List<UploadFileHelper> createPDFImages(List<UploadFileHelper> fileList, InputStream inputStream)
throws InvalidPasswordException, IOException, LimitException {
LOGGER.info("START createPDFImages");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PDDocument document = null;
try {
document = PDDocument.load(inputStream, MemoryUsageSetting.setupTempFileOnly());
PDFRenderer renderer = new PDFRenderer(document);
int numberPages = document.getNumberOfPages();
if (numberPages == 0)
return null;
if (numberPages > 10) {
throw new LimitException("Die PDF darf nicht mehr als 10 Seiten haben!");
}
for (int i = 1; i <= numberPages; i++) {
UploadFileHelper original = new UploadFileHelper();
byte[] targetStream = convertPDFtoImage(inputStream, renderer, baos, i);
ByteArrayInputStream bis = new ByteArrayInputStream(targetStream);
StreamedContent streamedContent = new DefaultStreamedContent(bis, "image/jpg",
UUID.randomUUID().toString());
original.setStreamFile(streamedContent);
fileList.add(original);
}
} finally {
if (document != null) {
try {
document.close();
baos.close();
LOGGER.info("End convert PDF to Images process");
} catch (IOException e) {
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
}
}
LOGGER.info("END createPDFImages");
return fileList;
}
/**
* Convert Image to PDF
*
* @param targetStream
* @return
*/
private byte[] convertPDFtoImage(InputStream targetStream, PDFRenderer renderer, ByteArrayOutputStream baos,
int pageNumber) {
LOGGER.info("START convertPDFtoImage");
try {
BufferedImage bi = renderer.renderImageWithDPI(pageNumber - 1, 100, ImageType.RGB);
ImageIO.write(bi, "jpg", baos);
baos.flush();
} catch (Exception e) {
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
LOGGER.info("END convertPDFtoImage");
return baos.toByteArray();
}