- 导入依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.26</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.2</version>
</dependency>
- 代码
public static List<InputStream> pdf2Image(InputStream inputStream) {
List<InputStream> resultList = new ArrayList<>();
String fileName = "E:\\"+DateUtil.today()+ IdUtil.randomUUID() +".pdf";
PDDocument pdDocument = null;
PdfReader reader = null;
try {
FileUtil.writeFromStream(inputStream,new File(fileName),false);
pdDocument = PDDocument.load(new File(fileName));
PDFRenderer renderer = new PDFRenderer(pdDocument);
reader = new PdfReader(fileName);
int pages = reader.getNumberOfPages();
log.info("pdf总共多少页-----" + pages);
for (int i = 0; i < pages; i++) {
BufferedImage image = renderer.renderImageWithDPI(i, 150);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, "png", bos);
resultList.add(new ByteArrayInputStream(bos.toByteArray()));
IoUtil.close(bos);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
reader.close();
IoUtil.close(pdDocument);
IoUtil.close(inputStream);
FileUtil.del(fileName);
}
return resultList;
}