<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.28</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
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.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
@Slf4j
public class Pdf2ImageUtil {
private static byte[] pdf2Image(byte[] pdfBytes) throws IOException {
PDDocument doc = null;
ByteArrayOutputStream baos = null;
try {
doc = PDDocument.load(pdfBytes);
int pageCount = doc.getNumberOfPages();
log.info("PDF转图片流,总页数:{}", pageCount);
PDFRenderer pdfRenderer = new PDFRenderer(doc);
BufferedImage pdfImage = null;
int y = 0;
List<BufferedImage> list = new ArrayList<>(pageCount);
int totalHeight = 0;
if (pageCount > 0) {
for (int i = 0; i < pageCount; i++) {
BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 100, ImageType.RGB);
totalHeight += bim.getHeight();
list.add(bim);
}
}
for (BufferedImage bim : list) {
if (Objects.isNull(pdfImage)) {
pdfImage = new BufferedImage(bim.getWidth(), totalHeight, BufferedImage.TYPE_INT_RGB);
}
pdfImage.getGraphics().drawImage(bim, 0, y, null);
y += bim.getHeight();
}
if (pdfImage != null) {
baos = new ByteArrayOutputStream();
ImageIO.write(pdfImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
log.info("PDF转图片流成功");
return imageInByte;
}
return null;
} catch (Exception e) {
log.error("PDF转图片流失败:{}", e.getMessage());
e.printStackTrace();
} finally {
if (ObjectUtil.isNotNull(baos)) {
baos.close();
}
if (ObjectUtil.isNotNull(doc)) {
doc.close();
}
}
return null;
}
public static String image2Base64(String filePath) throws IOException {
byte[] pdfBytes = HttpUtil.createGet(filePath).execute().bodyBytes();
byte[] imageBytes = Pdf2ImageUtil.pdf2Image(pdfBytes);
return getFileContentAsBase64Urlencoded(imageBytes);
}
private static String getFileContentAsBase64(byte[] imageBytes) {
return Base64.getEncoder().encodeToString(imageBytes);
}
private static String getFileContentAsBase64Urlencoded(byte[] imageBytes) throws IOException {
return URLEncoder.encode(getFileContentAsBase64(imageBytes), "utf-8");
}
}