本文基于fontbox-2.0.12.jar、pdfbox-2.0.12.jar实现pdf文件转为图片
public String pdfParserImg(String pdfPath,String imgPath,String imgType) throws IOException{
File file = new File(imgPath);
if(file.exists()){
return "已存在";
}
InputStream byteInputStream = null;
FileInputStream inputStream =null;
ImageOutputStream imOut = null;
ByteArrayOutputStream bs = null;
FileOutputStream fops = null;
try {
inputStream = new FileInputStream(new File(pdfPath));
PDDocument document = PDDocument.load(inputStream);
PDFRenderer renderer= new PDFRenderer(document);
int pageCount = document.getNumberOfPages();
if (pageCount > 0) {
BufferedImage image = renderer.renderImage(0, 2.0f);
image.flush();
bs = new ByteArrayOutputStream();
imOut = ImageIO.createImageOutputStream(bs);
ImageIO.write(image, imgType, imOut);
byteInputStream = new ByteArrayInputStream(bs.toByteArray());
}
fops = new FileOutputStream(new File(imgPath));
fops.write(readInputStream(byteInputStream));
fops.flush();
} catch (Exception e) {
logger.error("pdf转换为image出现异常",e);
throw new IOException(e);
}finally{
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(bs);
if(imOut != null){
imOut.close();
}
IOUtils.closeQuietly(byteInputStream);
IOUtils.closeQuietly(fops);
}
return imgPath;
}
public byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
return outStream.toByteArray();
}