maven依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.20</version>
</dependency>
工具类
package com.prust.server.utils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PdfToImageUtil {
private static final Integer DPI = 100;
private static final String IMG_TYPE = "png";
public static List<byte[]> pdfToImage(byte[] fileContent) throws IOException {
List<byte[]> result = new ArrayList<>();
try (PDDocument document = PDDocument.load(fileContent)) {
PDFRenderer renderer = new PDFRenderer(document);
for (int i = 0; i < document.getNumberOfPages(); ++i) {
BufferedImage bufferedImage = renderer.renderImageWithDPI(i, DPI);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, IMG_TYPE, out);
result.add(out.toByteArray());
}
}
return result;
}
}
测试代码
@Test
public void testServer() throws SQLException {
File file = new File("C:\\Users\\Administrator\\Desktop\\download (1).pdf");
byte [] bytes;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
int size=fis.available();
bytes=new byte[size];
fis.read(bytes);
System.out.println(PdfToImageUtil.pdfToImage(bytes));
List<byte[]> list = PdfToImageUtil.pdfToImage(bytes);
for (byte[] bytes1 : list) {
buff2Image(bytes1,"F:\\test" + new Random().nextInt(10) + ".jpg");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}