office 文档转pdf

本地先安装 金山wps,并确保可用

工程目录

1、使用前,先执行install.bat 安装jacob 到maven本地仓库

2、复制

jacob-1.18-M2-x64.dll
jacob-1.18-M2-x86.dll

到jdk的bin目录

maven的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.xiaojf.util</groupId>
    <artifactId>office-converter-util</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>jacob</groupId>
            <artifactId>jacob</artifactId>
            <version>1.18-M2</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
    </dependencies>
</project>

工具类

package cn.xiaojf.util;

import java.io.File;
import java.util.UUID;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.apache.commons.lang3.StringUtils;

/**
 * office 文档转换成pdf工具类,通过jacob调用wps转换文档
 * @author xiaojf 2017/12/2 8:29
 */
public class OfficeConverterUtil {

    private static final int WDFO_RMATPDF = 17;
    private static final int XLTYPE_PDF = 0;
    private static final int PPT_SAVEAS_PDF = 32;
    public static final int WORD_HTML = 8;
    public static final int WORD_TXT = 7;
    public static final int EXCEL_HTML = 44;
    public static final int PPT_SAVEAS_JPG = 17;
    // private static final int msoTrue = -1;
    // private static final int msofalse = 0;

    private static ActiveXComponent wordApp = null;
    private static ActiveXComponent excelApp = null;
    private static ActiveXComponent pptApp = null;
    private static ActiveXComponent ppApp = null;

    static {
        wordApp = new ActiveXComponent("Word.Application");
        wordApp.setProperty("Visible", new Variant(false));

        excelApp = new ActiveXComponent("Excel.Application");
        excelApp.setProperty("Visible", false);

        pptApp = new ActiveXComponent("KWPP.Application");
        ppApp = new ActiveXComponent("PowerPoint.Application");
    }

    /**
     * office文件转换成pdf,根据后缀名识别转换类型
     * @param inputFilePath 输入文件绝对路径
     * @param pdfPath 输出文件绝对路径
     * @return 转换是否成功,true 成功,false 不成功
     * @author xiaojf 2017/12/2 8:30
     */
    public static boolean officeFileConverterToPdf(String inputFilePath, String pdfPath) {
        if (StringUtils.isBlank(inputFilePath) || StringUtils.isBlank(pdfPath) || StringUtils.isBlank(getFileSufix(inputFilePath))) {
            return false;
        }

        String suffix = getFileSufix(inputFilePath);

        File file = new File(inputFilePath);
        if (!file.exists()) {
            return false;
        }

        // PDF如果不存在则创建文件夹
        file = new File(getFilePath(pdfPath));
        if (!file.exists()) {
            file.mkdir();
        }

        // 如果输入的路径为PDF 则生成失败
        if (suffix.equals("pdf")) {
            System.out.println("PDF not need to convert!");
            return false;
        }

        if (suffix.equals("doc") || suffix.equals("docx") || suffix.equals("txt")) {
            return wordToPDF(inputFilePath, pdfPath);
        } else if (suffix.equals("xls") || suffix.equals("xlsx")) {
            return excelToPdf(inputFilePath, pdfPath);
        } else if (suffix.equals("ppt") || suffix.equals("pptx")) {
            return pptToPdf(inputFilePath, pdfPath);
            // return ppt2PDF(argInputFilePath, argPdfPath);
        }

        return false;
    }

    /**
     * word 转 pdf
     * @param wordPath 输入文件绝对路径
     * @param pdfPath 输出文件绝对路径
     * @return 转换是否成功,true 成功,false 不成功
     * @author xiaojf 2017/12/2 8:30
     */
    public static boolean wordToPDF(String wordPath, String pdfPath) {

        try {
            Dispatch docs = Dispatch.get(wordApp, "Documents").toDispatch();
            // long pdfStart = System.currentTimeMillis();
            Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
                    new Object[]{wordPath, new Variant(false), new Variant(true)}, new int[1]).toDispatch();

            deletePdf(pdfPath);

            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{pdfPath, new Variant(WDFO_RMATPDF)},
                    new int[1]);
            // long pdfEnd = System.currentTimeMillis();
            if (null != doc) {
                Dispatch.call(doc, "Close", false);
            }
        } catch (Exception e) {
            e.printStackTrace();

        } /*
             * finally { wordApp.invoke("Quit"); }
             */
        return true;
    }

    /**
     * excel 转 pdf
     * @param inputFile 输入文件绝对路径
     * @param pdfFile 输出文件绝对路径
     * @return 转换是否成功,true 成功,false 不成功
     * @author xiaojf 2017/12/2 8:30
     */
    public static boolean excelToPdf(String inputFile, String pdfFile) {

        try {

            deletePdf(pdfFile);

            Dispatch excels = excelApp.getProperty("Workbooks").toDispatch();
            Dispatch excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch();
            Dispatch.call(excel, "ExportAsFixedFormat", XLTYPE_PDF, pdfFile);
            Dispatch.call(excel, "Close", false);
        } catch (Exception e) {
            e.printStackTrace();
        } /*
             * finally { excelApp.invoke("Quit"); }
             */
        return true;
    }

    /**
     * ppt 转 pdf
     * @param inputFile 输入文件绝对路径
     * @param pdfFile 输出文件绝对路径
     * @return 转换是否成功,true 成功,false 不成功
     * @author xiaojf 2017/12/2 8:30
     */
    public static boolean pptToPdf(String inputFile, String pdfFile) {
        // ComThread.InitSTA(true);

        try {
            // app.setProperty("Visible", false);
            Dispatch ppts = pptApp.getProperty("Presentations").toDispatch();
            Dispatch ppt = Dispatch.call(ppts, "Open", inputFile, true, // ReadOnly
                    // false, // Untitled指定文件是否有标题
                    false// WithWindow指定文件是否可见
            ).toDispatch();
            Dispatch.invoke(ppt, "SaveAs", Dispatch.Method, new Object[]{pdfFile, new Variant(PPT_SAVEAS_PDF)},
                    new int[1]);
            Dispatch.call(ppt, "Close");
        } catch (Exception e) {
            e.printStackTrace();
        } /*
             * finally { pptApp.invoke("Quit"); }
             */

        return true;
    }

    /**
     * ppt 转 图片
     * @param inputFile 输入文件绝对路径
     * @param imgFile 输出文件绝对路径
     * @return 转换是否成功,true 成功,false 不成功
     * @author xiaojf 2017/12/2 8:30
     */
    public static boolean pptToImg(String inputFile, String imgFile) {
        // 打开word应用程序

        try {
            // 设置word不可见,office可能有限制
            // app.setProperty("Visible", false);
            // 获取word中国所打开的文档,返回Documents对象
            Dispatch files = ppApp.getProperty("Presentations").toDispatch();
            // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
            Dispatch file = Dispatch.call(files, "open", inputFile, true, true, false).toDispatch();
            // 调用Document对象的SaveAs方法,将文档保存为pdf格式
            // Dispatch.call(doc, "ExportAsFixedFormat", outputFile,
            // PPT_TO_PDF);
            Dispatch.call(file, "SaveAs", imgFile, PPT_SAVEAS_JPG);
            // 关闭文档
            // Dispatch.call(file, "Close", false);
            Dispatch.call(file, "Close");
            // 关闭word应用程序
            // app.invoke("Quit", 0);
        } catch (Exception e) {
            e.printStackTrace();
        } /*
             * finally { ppApp.invoke("Quit"); }
             */

        return true;
    }

    /**
     * 获取文件扩展名
     * @param filePath
     * @author xiaojf 2017/12/2 8:35
     */
    public static String getFileSufix(String filePath) {
        int splitIndex = filePath.lastIndexOf(".");
        return filePath.substring(splitIndex + 1);
    }

    /**
     * 获取文件路径
     * @param filePath
     * @author xiaojf 2017/12/2 8:37
     */
    public static String getFilePath(String filePath) {
        int pathIndex = filePath.lastIndexOf("/");
        return filePath.substring(0, pathIndex);
    }

    /**
     *  如果目标文件存在,则删除
     *  @param pdfPath
     * @author xiaojf 2017/12/2 8:34
     */
    private static void deletePdf(String pdfPath) {
        File pdfFile = new File(pdfPath);
        if (pdfFile.exists()) {
            pdfFile.delete();
        }
    }

    public static void main(String[] args) {
        OfficeConverterUtil.wordToPDF("D:\\word2pdf\\1.doc",
                "D:\\word2pdf\\pdf\\" + UUID.randomUUID().toString() + ".doc.pdf");
        OfficeConverterUtil.wordToPDF("D:\\word2pdf\\1.docx",
                "D:\\word2pdf\\pdf\\" + UUID.randomUUID().toString() + ".docx.pdf");
        OfficeConverterUtil.pptToPdf("D:\\word2pdf\\1.ppt",
                "D:\\word2pdf\\pdf\\" + UUID.randomUUID().toString() + ".ppt.pdf");
        OfficeConverterUtil.pptToPdf("D:\\word2pdf\\1.pptx",
                "D:\\word2pdf\\pdf\\" + UUID.randomUUID().toString() + ".pptx.pdf");
        OfficeConverterUtil.wordToPDF("D:\\word2pdf\\1.rtf",
                "D:\\word2pdf\\pdf\\" + UUID.randomUUID().toString() + ".rtf.pdf");
        OfficeConverterUtil.wordToPDF("D:\\word2pdf\\1.txt",
                "D:\\word2pdf\\pdf\\" + UUID.randomUUID().toString() + ".txt.pdf");
        OfficeConverterUtil.excelToPdf("D:\\word2pdf\\1.xls",
                "D:\\word2pdf\\pdf\\" + UUID.randomUUID().toString() + ".xls.pdf");
        OfficeConverterUtil.excelToPdf("D:\\word2pdf\\1.xlsx",
                "D:\\word2pdf\\pdf\\" + UUID.randomUUID().toString() + ".xlsx.pdf");

        OfficeConverterUtil.pptToImg("D:\\word2pdf\\1.ppt",
                "D:\\word2pdf\\pdf\\" + UUID.randomUUID().toString() + ".ppt.jpg");

        wordApp.invoke("Quit");
        wordApp.safeRelease();
        excelApp.invoke("Quit");
        excelApp.safeRelease();
        pptApp.invoke("Quit");
        pptApp.safeRelease();
        ppApp.invoke("Quit");
        ppApp.safeRelease();

    }

}

转前

转后

源码下载

https://gitee.com/xiaojf/office-converter-util.git
时间: 2024-08-02 11:49:57

office 文档转pdf的相关文章

Java实现web在线预览office文档与pdf文档实例

https://yq.aliyun.com/ziliao/1768?spm=5176.8246799.blogcont.24.1PxYoX 摘要: 本文讲的是Java实现web在线预览office文档与pdf文档实例, 1.首先我们需要找到可以把office转换成pdf的方法,查找资料发现有openoffice这一软件可以把office转换成pdf,这一软件先下载下来,然后记住自己安装的在那个位置.然后在cmd环境下进入安装目录的program目 云计算 云服务器ECS 大数据 建站 备案 文档

Java实现office文档与pdf文档的在线预览功能

最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完.压力略大.后面查找百度资料.以及在同事与网友的帮助下,四天多把它做完.查找资料发现我们要实现的过程就是把office转换成pdf,当然pdf就不用转换了.然后在pdf转换为swf文件,在浏览器实现预览swf文件.整个过程就是这样,看起来很简单,实际操作起来会出现各种问题.下面我就把自己写的这一小功能记录下来. 1.首先我们需要找到可以把office转换成pdf的方法

office文档与pdf文件如何转为jpg图片

有些文档需要把内容输出成图片文件进行发送或是查看,也就是把像office文档以及pdf这类的文档转换成jpg图片的格式,我们都知道这些文档是不能直接保存输出成图片文件的,那要怎样操作才可以将这些文档快速的转为图片文件呢? 通过pdf转换成jpg软件可以将文档的内容输出成为图片的形式.打开转换软件后在左侧的第一个转换类别中选择“文件转图片”.一般转换的图片都是jpg格式. 添加文件既可以添加pdf格式的文件,也能添加office文档进行转换,并且对转换的文件没有要求和限制,文档可以是加密的或者扫描

Java中几种office文档转pdf的方式

最近公司要做office的文档,搜集了几种office文档转pdf的方式,简单的做下总结 我主要尝试了三种方式:openoffice,aspose,jacob 对他们进行了大文件,小文件,在linux,在windows,转换txt,excel,word,ppt的测试. 一.aspose:这种方式在目前来看应该是最好的,无论是转换的速度还是成功的概率,还支持的文件类型. (1)使用: 这种方式使用很简单,引入jar包就可以直接使用 代码: 源码,jar包在最后提供 package aspose;

linux下使用libreoffice将Office文档转PDF

Linux下可以通过libreoffice将常见的office文档转换成pdf文件,具体步骤如下: 1.安装libreoffice wget http://free.nchc.org.tw/tdf/libreoffice/stable/5.4.6/rpm/x86/LibreOffice_5.4.6_Linux_x86_rpm.tar.gz tar zxvf LibreOffice_5.4.6_Linux_x86_rpm.tar.gz sudo yum install LibreOffice_5.

C#实现office文档转换为PDF格式

需要安装office 2007 还有一个office2007的插件OfficeSaveAsPDFandXPS 下载地址 [url]http://www.microsoft.com/downloads/details.aspx?FamilyId=4D951911-3E7E-4AE6-B059-A2E79ED87041&displaylang=en[/url] 这是一个微软官方出的office插件. office2010里好像能直接将文件另存为.PDF格式的 安装好之后,打开VS,以VS2005为例

各种PDF转换问题(二).将OFFICE文档转为PDF文档

原则上说,PDF一旦创建,其本身是不可以修改的(某些操作,如批注等,则不属于此范围),又因为PDF有轻量,格式通用,允许包含的内容丰富等诸多优点,故很多企事业单位都喜欢将PDF作为最后的文档发放格式.OFFICE转PDF,则成了一个很常用的操作. OFFICE转PDF的手段很多,但最主流的,可能有这么三种: 1.使用微软的免费OFFICE插件SaveAsPDFandXPS.这个插件可以直接到微软官网下载,特点是免费,转换风险低.插件安装好之后,会在OFFICE开始菜单中,"另存为"子项

libreoffice转office文档为pdf文档

libreoffice5.0 --invisible --convert-to pdf:writer_pdf_Export --outdir  "/root/" "bb.xls" 九域技术朱亮亮 2015/12/1 10:11:57 Options:--minimized    keep startup bitmap minimized.--invisible    no startup screen, no default document and no UI.-

java将office文档pdf文档转换成swf文件在线预览

java将office文档pdf文档转换成swf文件在线预览 第一步,安装openoffice.org   openoffice.org是一套sun的开源office办公套件,能在widows,linux,solaris等操作系统上执行. 主要模块有writer(文本文档),impress(演示文稿),Calc(电子表格),Draw(绘图),Math(公式),base(数据库) 笔者下载的是openoffice.org 3.3.0.下载完直接安装即可.      但是,我们还需要启动openof