1、首先安装openoffice(安装包可在我的资源中查到名称:(openoffice))
2、安装完成后cmd 执行命令
(1)cd C:\Program Files (x86)\openoffice\program
(2)soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
3、代码如下(完整工程刻在我的资源中查找名称(doc转PDF),100%可直接使用)
import java.io.File;
import java.io.FilenameFilter;
import com.shunan.WordToPDF.TestThread;
public class Word2PDFUtil {
/**
* @param dirs doc转换文件夹,批量转换
*/
public static void word2Pdf(String dirs){
File dir = new File(dirs);
File[] files = dir.listFiles(new WordFilenameFilter());
//遍历文件夹方式
if (files == null||files.length==0){
throw new NullPointerException("该路径下没有可转换的文件");
}
for (int i = 0; i < files.length; i++) {
String strFileName = files[i].getAbsolutePath().toLowerCase();
TestThread t1 = new WordToPDF.TestThread();
//输入文件名
t1.setInputFile(new File(strFileName));
//获得"."前面的文件名并将其输入为PDF
t1.setOutputFile(new File(strFileName.substring(0,strFileName.indexOf("."))+".pdf"));
t1.start();
}
}
/**
* @param orgfileName 原始文件名
* @param descFileName 生成pdf文件名
*/
public static void word2Pdf(String orgfileName, String descFileName) {
if(!isWord(orgfileName)||descFileName==null){
throw new IllegalArgumentException("原始文件名不是可转换文档,或者descFileName为空");
}
TestThread t1 = new WordToPDF.TestThread();
// 输入文件名
t1.setInputFile(new File(orgfileName));
// 获得"."前面的文件名并将其输入为PDF
t1.setOutputFile(new File(descFileName.substring(0, descFileName
.indexOf("."))
+ ".pdf"));
t1.start();
}
static class WordFilenameFilter implements FilenameFilter{
@Override
//只转换word文档
public boolean accept(File dir, String name) {
return isWord(name);
}
}
/**
* @param name 文件名
* @return 判断是否为doc word文档
*/
private static boolean isWord(String name){
return name.endsWith(".doc")||name.endsWith(".docx")||name.endsWith(".wps")||name.endsWith(".txt");
//return true;
}
}
4、效果图