1、下载开源工具LibreOffice,可选择window和linux,这里我选择的是(LibreOffice_5.3.7_Win_x64.msi)
2、按照提示安装好后,配置环境变量path,值为”..\LibreOffice 5\program”
3、编写java代码:
3.1、CommandResult .java:
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
/**
* 描述:执行命令返回值
*
* @author ssl
* @create 2017/12/12 11:05
*/
public class CommandResult {
int ret = 0;
List<String> outLines;
List<String> errLines;
IOException exception;
String command;
public CommandResult() {
}
public int getRet() {
return this.ret;
}
public void setRet(int ret) {
this.ret = ret;
}
public List<String> getOutLines() {
return this.outLines;
}
public void setOutLines(List<String> outLines) {
this.outLines = outLines;
}
public List<String> getErrLines() {
return this.errLines;
}
public void setErrLines(List<String> errLines) {
this.errLines = errLines;
}
public IOException getIOException() {
return this.exception;
}
public void setIOException(IOException exception) {
this.exception = exception;
}
public String getCommand() {
return this.command;
}
public void setCommand(String command) {
this.command = command;
}
public String getOutput() {
StringBuffer output = new StringBuffer();
Iterator var2 = this.outLines.iterator();
String line;
while (var2.hasNext()) {
line = (String) var2.next();
if (trimToNull(line) != null) {
output.append(line).append("\r\n");
}
}
var2 = this.errLines.iterator();
while (var2.hasNext()) {
line = (String) var2.next();
if (trimToNull(line) != null) {
output.append(line).append("\r\n");
}
}
return output.toString();
}
public static String trimToNull(String str) {
String ts = trim(str);
return isEmpty(ts) ? null : ts;
}
public static String trim(String str) {
return str == null ? null : str.trim();
}
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
}
3.2、CommandUtils.java:
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 描述:执行命令行工具类
*
* @author ssl
* @create 2017/12/12 11:05
*/
public class CommandUtils {
static Pattern p = Pattern.compile("error=(\\d+),");
public CommandUtils() {
}
public static CommandResult execute(String... args) {
CommandResult commandResult = new CommandResult();
StringBuffer cmd = new StringBuffer();
for (int i = 0; i < args.length; ++i) {
if (i == 0) {
cmd.append(args[i]);
} else {
cmd.append(" ").append(args[i]);
}
}
commandResult.setCommand(cmd.toString());
Process process = null;
try {
process = (new ProcessBuilder(args)).start();
} catch (IOException var8) {
Matcher m = p.matcher(var8.getMessage());
if (m.find()) {
commandResult.setRet(Integer.valueOf(m.group(1)).intValue());
commandResult.setIOException(var8);
} else {
commandResult.setRet(-1);
commandResult.setIOException(var8);
}
return commandResult;
}
try {
commandResult.setOutLines(IOUtils.readLines(process.getInputStream()));
commandResult.setErrLines(IOUtils.readLines(process.getErrorStream()));
return commandResult;
} catch (IOException var7) {
commandResult.setRet(-1);
commandResult.setIOException(var7);
return commandResult;
}
}
}
3.3、PdfUtils.java,该类需要依赖commons-io、commons-lang3工具包
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import java.io.*;
import java.util.UUID;
/**
* 描述:pdf工具类
*
* @author ssl
* @create 2017/12/12 11:09
*/
public class PdfUtils {
public static byte[] fileToPdf(String docPath) throws Exception {
byte[] docBuf = IOUtils.toByteArray(new FileInputStream(docPath));
return fileToPdf(docBuf);
}
public static byte[] fileToPdf(byte[] docBuf) throws Exception {
byte[] pdfBuf = null;
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
String fileName = UUID.randomUUID().toString();
File fileDoc = new File(tempDirectory.getAbsolutePath() + File.separator + fileName + ".doc");
File filePdf = new File(tempDirectory.getAbsolutePath() + File.separator + fileName + ".pdf");
System.out.println(filePdf.getPath());
IOUtils.write(docBuf, new FileOutputStream(fileDoc));
String command = "soffice";
if (SystemUtils.IS_OS_MAC_OSX) {
command = "/Applications/LibreOffice.app/Contents/MacOS/soffice";
} else if (SystemUtils.IS_OS_WINDOWS) {
command = "soffice";
}
CommandResult commandResult = CommandUtils.execute(command, "--headless", "--convert-to",
"pdf:writer_pdf_Export", "--outdir", System.getProperty("java.io.tmpdir"),
fileDoc.getAbsolutePath());
if (commandResult.getRet() == 0) {
if (filePdf.exists() && filePdf.length() > 0) {
pdfBuf = new byte[(int) filePdf.length()];
IOUtils.readFully(new FileInputStream(filePdf), pdfBuf);
// 删除临时文件
FileWriter fw;
try {
fw = new FileWriter(fileDoc);
fw.write("");
fw.close();
fileDoc.delete();
fw = new FileWriter(filePdf);
fw.write("");
fw.close();
filePdf.delete();
} catch (Exception e) {
e.printStackTrace();
}
return pdfBuf;
} else {
String output = commandResult.getOutput();
System.out.println(commandResult.getCommand() + "\r\n" + output);
throw new IOException(output);
}
} else {
System.out.println(commandResult.getIOException());
throw commandResult.getIOException();
}
}
/**
* 文件(word,excel,图片等)转pdf
*
* @param filePath 文件完整路径(包含文件名),eg:<br>c:/file/doc/1.doc
* @param pdfPath 存放pdf文件的路径,eg:<br>c:/file/pdf
* @return
* @throws IOException
*/
public static String fileToPdf(String filePath, String pdfPath) throws IOException {
/** 获取文件名 */
File file = new File(filePath);
String fileName = FilenameUtils.getBaseName(filePath) + ".pdf";
File pdfFile = new File(pdfPath, fileName);
/** 定义执行命令语句 */
String command = "soffice";
if (SystemUtils.IS_OS_MAC_OSX) {
command = "/Applications/LibreOffice.app/Contents/MacOS/soffice";
} else if (SystemUtils.IS_OS_WINDOWS) {
command = "soffice";
}
CommandResult commandResult = CommandUtils.execute(command, "--headless", "--convert-to",
"pdf:writer_pdf_Export", "--outdir", pdfPath, file.getAbsolutePath());
if (commandResult.getRet() == 0) {
if (pdfFile.exists() && pdfFile.length() > 0) {
/** 转为pdf成功 */
return pdfFile.getPath();
} else {
String output = commandResult.getOutput();
System.out.println(commandResult.getCommand() + "\r\n" + output);
throw new IOException(output);
}
} else {
System.out.println(commandResult.getIOException());
throw commandResult.getIOException();
}
}
public static void main(String[] args) {
String filePath = "F:\\libreoffice\\file\\1.doc";
String pdfPath = "F:\\libreoffice\\file";
try {
pdfPath = fileToPdf(filePath, pdfPath);
System.out.println(pdfPath);
//注意,下面方法有可能会执行不成功的,原因是生成文件和pdf的目录系统不允许写入,
//所以一般还是手动设置好文件和pdf目录
//byte[] pdfbuf = fileToPdf(filePath);
//FileUtils.writeByteArrayToFile(new File("C:\\Users\\49383\\Desktop\\工作\\pp22.pdf"), pdfbuf);
System.out.println("success!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:执行不成功时候,最好是将执行的cmd命令复制出来,指定一个可写入的目录,在cmd窗口进行调试,还可以查看soffice的帮助说明:soffice –help