@PostMapping("/convertToBase64/{fileRename}")
public AjaxResult convertToBase64(@PathVariable String fileRename) throws IOException {
List<String> base64Images = new ArrayList<>();
if (StringUtils.isEmpty(fileRename))
return AjaxResult.error("文件不能为空");
String result = businessManagementService.detailsNodeDataDownload(fileRename);
if (StringUtils.isEmpty(result) || result.contains("access")){
return AjaxResult.error("下载失败!");
}
String fileUrl = result;
int dotIndex = fileRename.lastIndexOf('.');
String fileType = fileRename.substring(dotIndex + 1);
byte[] fileBytes;
if ("pdf".equalsIgnoreCase(fileType)) {
// 对PDF文件进行转换
base64Images = convertPdfToBase64(fileUrl);
} else if ("img".equalsIgnoreCase(fileType)||"png".equalsIgnoreCase(fileType)) {
// 对图片文件进行转换
fileBytes = convertImageToBase64(fileUrl);
String base64File = "data:image/png;base64," + Base64.getEncoder().encodeToString(fileBytes);
base64Images.add(base64File);
} else if ("doc".equalsIgnoreCase(fileType)||"docx".equals(fileType)) {
// 对Word文件进行转换
base64Images = convertWordToBase64(fileUrl);
} else {
return error("Unsupported file type");
}
return success(base64Images);
}
private List<String> convertPdfToBase64(String imageUrl) throws IOException {
// 从远程 URL 获取 PDF 文档
URL url = new URL(imageUrl);
try (PDDocument document = PDDocument.load(url.openStream())) {
int numPages = document.getNumberOfPages();
List<String> base64Images = new ArrayList<>();
// 使用 PDFBox 将 PDF 转换为 BufferedImage
PDFRenderer renderer = new PDFRenderer(document);
for (int pageIndex = 0; pageIndex < numPages; pageIndex++) {
BufferedImage image = renderer.renderImage(pageIndex);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
byte[] imageBytes = baos.toByteArray();
String base64Image = "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes);
base64Images.add(base64Image);
}
return base64Images;
}
}
private byte[] convertImageToBase64(String imageUrl) throws IOException {
URL url = new URL(imageUrl);
BufferedImage image = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
return baos.toByteArray();
}
private List<String> convertWordToBase64(String wordFilePath) throws IOException {
// 创建Document实例
Document doc = new Document();
List<String> base64Images = new ArrayList<>();
InputStream inputStream = new URL(wordFilePath).openStream();
// 加载Word文档
doc.loadFromStream(inputStream, FileFormat.Auto);
BufferedImage[] images = doc.saveToImages(0, doc.getPageCount(), ImageType.Bitmap, 500, 500);
for (BufferedImage image : images) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
String base64Image = "data:image/png;base64," + Base64.getEncoder().encodeToString(baos.toByteArray());
base64Images.add(base64Image);
// base64Images.add("base64Image");
}
return base64Images;
}