document4j — это библиотека Java, которая может конвертировать документы в другой формат документов.
https://github.com/documents4j/documents4j
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.6.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.1.5</version>
</dependency>
</dependencies>
@RequestMapping("/to")
@RestController
public class PdfController {
/**
* doc文件转pdf
*
* @param path 文件路径
*/
@RequestMapping("/doc2pdf")
public ResponseEntity<byte[]> doc2pdfFileUpload(String path) throws IOException {
URL url = new URL(path);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
return doc2Pdf(inputStream, ".doc", "fileName.pdf");
}
/**
* docx、xlsx、转pdf
*
* @param fileType docx、doc、xls、xlsx
* @param fileName pdf名称
*/
public ResponseEntity<byte[]> doc2Pdf(InputStream docxInputStream, String fileType, String fileName) throws IOException {
// 转换后的pdf临时路径
File outputFile = new File("C:/Users/admin002/Desktop/folder/doc/" + fileName);
IConverter converter = LocalConverter.builder().build();
ResponseEntity<byte[]> fileResult = null;
try (OutputStream outputStream = Files.newOutputStream(outputFile.toPath());
// 导出pdf文件给前端
FileInputStream inputStream = new FileInputStream(outputFile);
) {
if (".docx".equals(fileType)) {
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
} else if (".doc".equals(fileType)) {
converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
} else if (".xls".equals(fileType)) {
converter.convert(docxInputStream).as(DocumentType.XLS).to(outputStream).as(DocumentType.PDF).execute();
} else if (".xlsx".equals(fileType)) {
converter.convert(docxInputStream).as(DocumentType.XLSX).to(outputStream).as(DocumentType.PDF).execute();
}
byte[] bytes = new byte[(int) outputFile.length()];
inputStream.read(bytes);
HttpHeaders headers = new HttpHeaders();
// 此处pdf名称需要传入
headers.set("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
fileResult = new ResponseEntity(bytes, headers, HttpStatus.OK);
} finally {
docxInputStream.close();
}
return fileResult;
}
}
Вышеупомянутый метод основан на MS Word и MS Excel в Windows, поэтому необходимо использовать Windows.
Сборка может быть запущена только если LocalConverter
:
- JVM работает на платформе MS Windows, которая поставляется с Microsoft Script Host для VBS.
- Версия MS Word должна быть 2007 или выше. Преобразование PDF поддерживается только в том случае, если установлен плагин PDF. Этот плагин включен в Word 2010 и более поздние версии MS Word.
Продолжение следует. . . .