pdf文件转图片,base64或保存到本地
pdf转图片,需要引入pdfbox依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
@RequestMapping("pdfToImg")
public void pdfToImg(){
PDDocument document = null;
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try{
inputStream = new FileInputStream(new File("F:\\贴纸.pdf"));
document = PDDocument.load(inputStream);
PDFRenderer renderer = new PDFRenderer(document);
int pageSize = document.getNumberOfPages();
String text = "";
// 一页一页读取
outputStream = new ByteArrayOutputStream();
for (int i = 0; i < pageSize; i++) {
//每一页通过分辨率和颜色值进行转化
BufferedImage bufferedImage = renderer.renderImageWithDPI(i, 300);
// ImageIO.write(bufferedImage,"png",new File("F:\\下载\\img_"+i+".png"));
ImageIO.write(bufferedImage,"png",outputStream);
outputStream.flush();
}
byte[] imagesBytes = outputStream.toByteArray();
String imageBase64 = Base64.getEncoder().encodeToString(imagesBytes);
System.out.println(imageBase64);
}catch (Exception e){
System.out.println(e.getMessage());
}finally {
try {
if (document != null) {
document.close();
}
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}