springboot word转pdf linux
时间: 2025-01-24 12:07:26 浏览: 51
### 实现Spring Boot应用在Linux下将Word文档转换为PDF
为了实现在Linux环境中通过Spring Boot应用程序完成Word到PDF的转换功能,可以采用Apache POI库处理Microsoft Word文件(.docx),并利用第三方工具如LibreOffice或JODConverter来执行实际的格式转换操作。
#### 添加依赖项
首先,在`pom.xml`中加入必要的Maven依赖:
```xml
<dependencies>
<!-- Apache POI for handling .docx files -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<!-- JODConverter to interact with LibreOffice/OpenOffice -->
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.0.0</version>
</dependency>
<!-- Optional: If using newer versions of jodconverter -->
<!--<dependency>-->
<!-- <groupId>fr.opensagres.xdocreport</groupId>-->
<!-- <artifactId>fr.opensagres-xdocreport-converter-jodconverter</artifactId>-->
<!-- <version>2.0.2</version>-->
<!--</dependency>-->
</dependencies>
```
#### 配置LibreOffice服务
确保安装了LibreOffice,并设置好环境变量以便Java程序能够找到它。可以通过命令行启动LibreOffice监听器作为后台进程:
```bash
soffice --headless --accept="socket,host=127.0.0.1,port=8100;urp;"
```
此命令使得LibreOffice可以在指定端口上等待来自其他应用程序的连接请求[^1]。
#### 编写控制器方法
创建一个新的RESTful API接口用于接收上传的`.docx`文件并将它们转换成`.pdf`:
```java
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@RestController
@RequestMapping("/api/convert")
public class ConverterController {
private static final String LO_PORT = "8100";
private static final String OUTPUT_DIR = "/tmp/";
@PostMapping(value="/word-to-pdf", consumes={"multipart/form-data"})
public ResponseEntity<String> convertDocToPdf(@RequestParam("file") MultipartFile file){
try {
File inputFile = new File(OUTPUT_DIR + file.getOriginalFilename());
File outputFile = new File(inputFile.getAbsolutePath().replace(".docx",".pdf"));
// Save uploaded file locally
file.transferTo(inputFile);
OfficeManager officeManager = LocalOfficeManager.builder()
.install()
.officeHome(new File("/usr/lib/libreoffice")) // Adjust path according to installation location
.portNumbers(Integer.parseInt(LO_PORT))
.build();
DocumentFormat docx = new DocumentFormat("MS Word 97/2000/XP", "docx");
DocumentFormat pdf = new DocumentFormat("PDF - Portable Document Format", "pdf");
ConversionTask task = new DefaultConversionTask(
new InputStreamSource(file.getInputStream()),
outputFile,
docx,
pdf);
officeManager.start();
converter.convert(task).execute();
// Clean up temporary files after conversion is done.
Files.deleteIfExists(inputFile.toPath());
return ResponseEntity.ok(outputFile.getPath());
} catch(Exception e) {
logger.error(e.getMessage(),e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
}
```
上述代码片段展示了如何构建一个简单的API端点,该端点接受多部分表单数据形式提交的Word文档(`.docx`),并通过调用外部LibreOffice实例将其转换为PDF格式[^2]。
阅读全文
相关推荐



















