1.引入依赖
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.8.12version>
dependency>
<dependency>
<groupId>org.apache.pdfboxgroupId>
<artifactId>pdfboxartifactId>
<version>2.0.26version>
dependency>
2.编写工具类
public class PdfUtil {
public static final int DEFAULT_DPI = 150;
public static List<BufferedImage> pdfConvertImageList(InputStream inputStream) {
PDDocument pdf = null;
try {
pdf = PDDocument.load(inputStream);
PDFRenderer pdfRenderer = new PDFRenderer(pdf);
int actSize = pdf.getNumberOfPages();
List<BufferedImage> picList = new ArrayList<>();
for (int i = 0; i < actSize; i++) {
BufferedImage image = pdfRenderer.renderImageWithDPI(i, DEFAULT_DPI, ImageType.RGB);
picList.add(image);
}
return picList;
} catch (IOException e) {
System.out.println("pdf转图片失败");
} finally {
IoUtil.close(pdf);
}
return Collections.emptyList();
}
public static List<InputStream> pdfConvertImageStreamList(InputStream inputStream,String imgType){
return pdfConvertImageList(inputStream).stream().map( bi ->ImgUtil.toStream(bi, imgType)).collect(Collectors.toList());
}
public static BufferedImage pdfConvertImage(InputStream inputStream){
return pdfConvertImageList(inputStream).stream().reduce( (bi1,bi2)->mergeImage(bi1,bi2,false)).get();
}
public static InputStream pdfConvertImageStream(InputStream inputStream,String imgType){
return ImgUtil.toStream(pdfConvertImage(inputStream),imgType);
}
private static BufferedImage mergeImage(BufferedImage img1, BufferedImage img2, boolean isHorizontal) {
int w1 = img1.getWidth();
int h1 = img1.getHeight();
int w2 = img2.getWidth();
int h2 = img2.getHeight();
int[] ImageArrayOne = new int[w1 * h1];
ImageArrayOne = img1.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1);
int[] ImageArrayTwo = new int[w2 * h2];
ImageArrayTwo = img2.getRGB(0, 0, w2, h2, ImageArrayTwo, 0, w2);
BufferedImage DestImage = null;
if (isHorizontal) {
DestImage = new BufferedImage(w1+w2, h1, BufferedImage.TYPE_INT_RGB);
DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1);
DestImage.setRGB(w1, 0, w2, h2, ImageArrayTwo, 0, w2);
} else {
DestImage = new BufferedImage(w1, h1 + h2, BufferedImage.TYPE_INT_RGB);
DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1);
DestImage.setRGB(0, h1, w2, h2, ImageArrayTwo, 0, w2);
}
return DestImage;
}
}
3.测试
public static void main(String[] args) {
InputStream inputStream = PdfUtil.pdfConvertImageStream(FileUtil.getInputStream("E:\\test.pdf"), ImgUtil.IMAGE_TYPE_PNG);
FileUtil.writeFromStream(inputStream,"E:\\test\\test.png");
}