import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
public class OfficeToPdf {
private static final int wdFormatPDF = 17;
private static final int xlTypePDF = 0;
private static final int ppSaveAsPDF = 32;
public static void main(String[] args) {
convert2PDF("I:\\使用方法.txt","I:\\使用方法.pdf");
public static boolean convert2PDF(String inputFile, String pdfFile) {
String suffix = getFileSufix(inputFile);
File file = new File(inputFile);
System.out.println("文件不存在!");
if (suffix.equals("pdf")) {
System.out.println("PDF not need to convert!");
OfficeToPdf officeToPdf = new OfficeToPdf();
if (suffix.equals("doc") || suffix.equals("docx")
|| suffix.equals("txt")) {
return officeToPdf.word2PDF(inputFile, pdfFile);
} else if (suffix.equals("ppt") || suffix.equals("pptx")) {
return officeToPdf.ppt2PDF(inputFile, pdfFile);
} else if (suffix.equals("xls") || suffix.equals("xlsx")) {
return officeToPdf.excel2PDF(inputFile, pdfFile);
System.out.println("文件格式不支持转换!");
public static String getFileSufix(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(splitIndex + 1);
public boolean word2PDF(String inputFile, String pdfFile) {
ActiveXComponent app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(docs, "Open", inputFile, false, true)
Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF
Dispatch.call(doc, "Close", false);
public boolean excel2PDF(String inputFile, String pdfFile) {
ActiveXComponent app = new ActiveXComponent("Excel.Application");
app.setProperty("Visible", false);
Dispatch excels = app.getProperty("Workbooks").toDispatch();
Dispatch excel = Dispatch.call(excels, "Open", inputFile, false,
Dispatch.call(excel, "ExportAsFixedFormat", xlTypePDF, pdfFile);
Dispatch.call(excel, "Close", false);
public boolean ppt2PDF(String inputFile, String pdfFile) {
ActiveXComponent app = new ActiveXComponent(
"PowerPoint.Application");
Dispatch ppts = app.getProperty("Presentations").toDispatch();
Dispatch ppt = Dispatch.call(ppts, "Open", inputFile, true,
Dispatch.call(ppt, "SaveAs", pdfFile, ppSaveAsPDF);
Dispatch.call(ppt, "Close");