前提:Windows环境
在项目中,有需求Word转PDF或者Excel转PDF,例举一个简单有效的转换工具。
Windows环境亲测有效。
Maven项目依赖:
<!-- https://mvnrepository.com/artifact/com.documents4j/documents4j-local -->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.1.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.documents4j/documents4j-transformer-msoffice-word -->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.1.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.documents4j/documents4j-transformer-msoffice-excel -->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-excel</artifactId>
<version>1.1.5</version>
</dependency>
示例代码如下:
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import java.io.*;
/**
* @description PDF转换工具类 仅支持Windows环境
*/
public class PdfConvertUtil {
/**
* @param sourceFilePath 源文件路径
* @param pdfFilePath PDF文件路径
* @description Word转PDF 仅支持Windows环境
*/
public static boolean word2pdf(String sourceFilePath, String pdfFilePath) {
boolean boo = false;
File inputFile = new File(sourceFilePath);
File outputFile = new File(pdfFilePath);
if (!inputFile.exists()) {
System.err.println("源文件不存在");
return boo;
}
if (!outputFile.exists()) {
try {
outputFile.createNewFile();
} catch (IOException e) {
System.err.println("PDF文件创建失败");
e.printStackTrace();
}
}
try {
InputStream inputStream = new FileInputStream(inputFile);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
converter.convert(inputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
outputStream.close();
boo = true;
} catch (Exception e) {
e.printStackTrace();
}
return boo;
}
/**
* @param sourceFilePath 源文件路径
* @param pdfFilePath PDF文件路径
* @description Excel转PDF 仅支持Windows环境
*/
public static boolean excel2pdf(String sourceFilePath, String pdfFilePath) {
boolean boo = false;
File inputFile = new File(sourceFilePath);
File outputFile = new File(pdfFilePath);
if (!inputFile.exists()) {
System.err.println("源文件不存在");
return boo;
}
if (!outputFile.exists()) {
try {
outputFile.createNewFile();
} catch (IOException e) {
System.err.println("PDF文件创建失败");
e.printStackTrace();
}
}
try {
InputStream inputStream = new FileInputStream(inputFile);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
converter.convert(inputStream).as(DocumentType.XLSX).to(outputStream).as(DocumentType.PDF).execute();
outputStream.close();
boo = true;
} catch (Exception e) {
e.printStackTrace();
}
return boo;
}
}