所需依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
代码:
import io.swagger.annotations.ApiOperation;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
@RestController
public class PngConversionController {
@ApiOperation("文件转换,图片转docx")
@PostMapping("/uploadPngConvert")
public ResponseEntity<byte[]> uploadPngConvert(@RequestPart("file") MultipartFile uploadedFile) throws Exception {
InputStream fileInputStream = uploadedFile.getInputStream();
BufferedImage bufferedImage = ImageIO.read(fileInputStream);
// 创建一个新的DOCX文档
XWPFDocument document = new XWPFDocument();
// 在docx文件中添加图片
XWPFRun run = document.createParagraph().createRun();
int format = XWPFDocument.PICTURE_TYPE_JPEG;
run.addPicture(new ByteArrayInputStream(uploadedFile.getBytes()), format, "image.jpg", Units.toEMU(bufferedImage.getWidth()), Units.toEMU(bufferedImage.getHeight()));
// 保存docx文件到 ByteArrayOutputStream
ByteArrayOutputStream docxOutputStream = new ByteArrayOutputStream();
document.write(docxOutputStream);
document.close();
// 将 ByteArrayOutputStream 中的内容作为字节数组返回
byte[] docxBytes = docxOutputStream.toByteArray();
// 设置响应头,指定文件名
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=output_docx_file.docx");
// 返回响应实体
return ResponseEntity.ok()
.headers(headers)
.contentLength(docxBytes.length)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(docxBytes);
}
}