Java Spring Boot PDF 上传并按页数重命名为图片保存
- 首先需要引入相关依赖,包括 Spring Boot、Apache Commons FileUpload 和 iTextPDF。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
- 创建一个 Controller 来处理文件上传请求,并将上传的文件保存到本地。
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "File is empty";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(file.getOriginalFilename());
Files.write(path, bytes);
return "File uploaded successfully";
} catch (IOException e) {
e.printStackTrace();
}
return "Error uploading file";
}
}
- 在上传文件的方法中,添加处理 PDF 文件的代码。使用 iTextPDF 库将 PDF 文件转换为多个图片,并将每个图片重命名为其页数。
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "File is empty";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(file.getOriginalFilename());
Files.write(path, bytes);
// Convert PDF to images and rename them by page number
PdfReader reader = new PdfReader(path.toString());
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
String imageName = "page_" + i + ".png";
FileOutputStream fos = new FileOutputStream(imageName);
Image image = Image.getInstance(reader, i);
BufferedImage bufferedImage = image.getBufferedImage();
ImageIO.write(bufferedImage, "png", fos);
fos.close();
}
return "File uploaded successfully";
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
return "Error uploading file";
}
- 完整的 Controller 代码如下:
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "File is empty";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(file.getOriginalFilename());
Files.write(path, bytes);
// Convert PDF to images and rename them by page number
PdfReader reader = new PdfReader(path.toString());
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
String imageName = "page_" + i + ".png";
FileOutputStream fos = new FileOutputStream(imageName);
Image image = Image.getInstance(reader, i);
BufferedImage bufferedImage = image.getBufferedImage();
ImageIO.write(bufferedImage, "png", fos);
fos.close();
}
return "File uploaded successfully";
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
return "Error uploading file";
}
}
原文地址: https://www.cveoy.top/t/topic/l3fp 著作权归作者所有。请勿转载和采集!