java使用openoffice/libreoffice进行office转pdf

    OpenOffice.org 是一套跨平台的办公室软件套件,能在 Windows、Linux、MacOS X (X11)、和 Solaris 等操作系统上执行。

它与各个主要的办公室软件套件兼容。OpenOffice.org 是自由软件,任何人都可以免费下载、使用、及推广它。官方文档:http://www.openoffice.org/zh-cn/

    LibreOffice 是一款功能强大的办公软件,默认使用开放文档格式 (OpenDocument Format , ODF), 并支持 *.docx, *.xlsx, *.pptx 等其他格式。
它包含了 Writer, Calc, Impress, Draw, Base 以及 Math 等组件,可用于处理文本文档、电子表格、演示文稿、绘图以及公式编辑。官方文档:https://zh-cn.libreoffice.org/

    JODConverter,是一个Java的OpenDocument文件转换器,可以进行许多文件格式的转换。它依赖于OpenOffice.org或者LibreOffice提供的服务来进行转换,它能将Microsoft Office文档(Word,Excel,PowerPoint)转换为PDF格式。

你可以将JODConverter内嵌在Java应用程序里,也可以单独作为命令行由脚本调用,更可以应用为网页程序或者Web Service以供网络应用。下载地址:https://sourceforge.net/projects/jodconverter/files/JODConverter/

 

office转换pdf

启动OpenOffice/LibreOffice的服务(本是同根生,启动服务方法一样;转换pdf都使用JODConverter,切换服务可以不用改代码)

进入openoffice/libreoffice安装目录,通过cmd启动一个soffice服务,启动的命令是soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;"

package com.feng.util;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import com.feng.bean.ResultCode;
import com.feng.date.DateTools;
import com.feng.error.MyException;
import lombok.extern.slf4j.Slf4j;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

import java.io.File;
import java.util.regex.Pattern;

/**
 * OpenOffice相关操作
 * Created by feng on 2020/10/22.
 */
@Slf4j
public class OpenOfficeUtil {

    /**
     * office转pdf (手动启服务soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;")
     *
     * @param sourceFile 源文件 office
     * @param destFile   目标文件 pdf
     * @return
     */
    public static void officeToPDF(String sourceFile, String destFile, String ip, Integer port) {
        try {
            File inputFile = new File(sourceFile);
            if (!inputFile.exists()) {
                // 找不到源文件, 则返回
                return;
            }
            // 如果目标路径不存在, 则新建该路径
            File outputFile = new File(destFile);
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
            //如果目标文件存在,则删除
            if (outputFile.exists()) {
                outputFile.delete();
            }
            OpenOfficeConnection connection = new SocketOpenOfficeConnection(ip, port);//"127.0.0.1", 8100
            connection.connect();
            log.info("OpenOffice连接时间:" + DateTools.now());
            long t1 = System.currentTimeMillis();
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(
                    connection);
            converter.convert(inputFile, outputFile);
            long t2 = System.currentTimeMillis();
            log.info("OpenOffice转换完成时间:{},耗时:{}ms", DateTools.now(), t2 - t1);
            connection.disconnect();
        } catch (Exception e) {
            log.error("officeToPDF错误:", e);
            throw new MyException(ResultCode.FAILURE, "officeToPDF错误");
        }
    }

    /**
     * 将Office文档转换为PDF. 需要安装OpenOffice (自动启服务)
     *
     * @param inputFilePath  源文件,绝对路径. 可以是Office2003-2007全部格式的文档, 包括.doc, .docx, .xls, .xlsx, .ppt, .pptx等.
     * @param outputFilePath 目标文件.绝对路径.
     */
    public static void office2pdf(String inputFilePath, String outputFilePath) {
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        String officeHome = getOfficeHome();
        //设置OpenOffice.org安装目录
        config.setOfficeHome(officeHome);
        //设置转换端口,默认为8100
        config.setPortNumbers(8100);
        //设置任务执行超时为60分钟
        config.setTaskExecutionTimeout(1000 * 60 * 60L);
        //设置任务队列超时为24小时
        config.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
        OfficeManager officeManager = config.buildOfficeManager();
        officeManager.start();
        log.info("office转换服务启动成功!{}", DateTools.now());
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        File inputFile = new File(inputFilePath);
        if (inputFile.exists()) {// 找不到源文件, 则返回
            File outputFile = new File(outputFilePath);
            if (!outputFile.getParentFile().exists()) { // 假如目标路径不存在, 则新建该路径
                outputFile.getParentFile().mkdirs();
            }
            converter.convert(inputFile, outputFile);
        }
        if (null != officeManager) {
            officeManager.stop();
            log.info("office转换服务完成。{}", DateTools.now());
        }
    }

    /**
     * 获取OpenOffice安装目录
     *
     * @return
     */
    public static String getOfficeHome() {
        String osName = System.getProperty("os.name");
        if (Pattern.matches("Linux.*", osName)) {
            return "/opt/openoffice";
        } else if (Pattern.matches("Windows.*", osName)) {
            return "C:/Program Files (x86)/OpenOffice 4";
        } else if (Pattern.matches("Mac.*", osName)) {
            return "/Application/OpenOffice.org.app/Contents";
        }
        return null;
    }

    public static void main(String[] args) {
        officeToPDF("d:/tmp/1.docx", "d:/tmp/1.pdf");
//        office2pdf("d:/tmp/1.docx", "d:/tmp/1.pdf"); 
    }
}

office转换html

只需要将后缀名从.pdf改为.html即可。

public static void main(String[] args) {
        officeToPDF("d:/tmp/1.docx", "d:/tmp/1.html");
//        office2pdf("d:/tmp/1.docx", "d:/tmp/1.html"); 
    }

maven配置

<dependency>
	<groupId>com.artofsolving</groupId>
	<artifactId>jodconverter</artifactId>
	<version>2.2.1</version>
</dependency>
<dependency>
	<groupId>org.openoffice</groupId>
	<artifactId>jurt</artifactId>
	<version>3.0.1</version>
</dependency>
<dependency>
	<groupId>org.openoffice</groupId>
	<artifactId>ridl</artifactId>
	<version>3.0.1</version>
</dependency>
<dependency>
	<groupId>org.openoffice</groupId>
	<artifactId>juh</artifactId>
	<version>3.0.1</version>
</dependency>
<dependency>
	<groupId>org.openoffice</groupId>
	<artifactId>unoil</artifactId>
	<version>3.0.1</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-jdk14</artifactId>
	<version>1.4.3</version>
</dependency>

Maven中只有 2.2.1版本,2.2.1版本有一个问题,那就是不兼容docx和pptx,想要使用2.2.1版本,需要修改一下 BasicDocumentFormatRegistry 类中的 getFormatByFileExtension方法:

1、新建包 com.artofsolving.jodconverter
2、新建类BasicDocumentFormatRegistry,复制下面代码

package com.artofsolving.jodconverter;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BasicDocumentFormatRegistry implements DocumentFormatRegistry {
    private List documentFormats = new ArrayList();

    public BasicDocumentFormatRegistry() {
    }

    public void addDocumentFormat(DocumentFormat documentFormat) {
        this.documentFormats.add(documentFormat);
    }

    protected List getDocumentFormats() {
        return this.documentFormats;
    }

    public DocumentFormat getFormatByFileExtension(String extension) {
        if (extension == null) {
            return null;
        } else {
            if (extension.indexOf("doc") >= 0) {
                extension = "doc";
            }
            if (extension.indexOf("ppt") >= 0) {
                extension = "ppt";
            }
            if (extension.indexOf("xls") >= 0) {
                extension = "xls";
            }
            String lowerExtension = extension.toLowerCase();
            Iterator it = this.documentFormats.iterator();

            DocumentFormat format;
            do {
                if (!it.hasNext()) {
                    return null;
                }

                format = (DocumentFormat)it.next();
            } while(!format.getFileExtension().equals(lowerExtension));

            return format;
        }
    }

    public DocumentFormat getFormatByMimeType(String mimeType) {
        Iterator it = this.documentFormats.iterator();

        DocumentFormat format;
        do {
            if (!it.hasNext()) {
                return null;
            }

            format = (DocumentFormat)it.next();
        } while(!format.getMimeType().equals(mimeType));

        return format;
    }
}

最后我使用了LibreOffice;先用了OpenOffice,发现ppt转换pdf会出现文字颜色不对的情况,白色变黑色,黑色变白色,其他颜色也成了黑白;用LibreOffice文字样式正常,只是一些绘图不正常,文档优先保证文字正常,所以最后用了LibreOffice。

excel转pdf会出现折行问题,请移步:解决excel转pdf出现的折行问题

安装及其他问题可看更多资料。

更多资料:

JODConverter 简单介绍

Java使用Openoffice将word、ppt转换为PDF

记录libreoffice实现office转pdf(适用于windows、linux)

【libreoffice】libreoffice实现office转pdf、html、jpg等格式数据

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
JodConverter 是一个 Java 库,用于将文档从一种格式换为另一种格式。它支持使用 OpenOfficeLibreOffice 进行换,而不需要安装 Microsoft Office。要使用 JodConverter 进行远程访问 OpenOffice,您需要执行以下步骤: 1. 安装 OpenOffice/LibreOffice 并启动服务。确保您的 OpenOffice/LibreOffice 实例已启动并在运行。 2. 在您的 Java 项目中添加 JodConverter 依赖项。您可以从 Maven 中央存储库下载 JodConverter JAR 文件,或者您可以将其添加到您的 Maven 依赖项中。 3. 在您的 Java 代码中创建一个 OfficeManager 实例,以便您可以连接到正在运行的 OpenOffice/LibreOffice 实例。以下是一个示例代码片段: ``` LocalOfficeManager officeManager = LocalOfficeManager.builder() .officeHome("/path/to/openoffice") .install() .build(); officeManager.start(); ``` 请注意,此代码使用 `LocalOfficeManager` 类,该类将连接到本地运行的 OpenOffice/LibreOffice 实例。如果您需要连接到远程 OpenOffice/LibreOffice 实例,请使用 `RemoteOfficeManager` 类。 4. 将您要换的文档传递给 JodConverter,然后指定要将其换为的格式。以下是一个示例代码片段: ``` File inputFile = new File("/path/to/input.docx"); File outputFile = new File("/path/to/output.pdf"); DocumentConverter converter = LocalConverter.builder() .officeManager(officeManager) .build(); converter.convert(inputFile).to(outputFile).execute(); ``` 在此示例中,将 `input.docx` 文件换为 `output.pdf` 文件。您可以将 `to()` 方法的参数更改为您要换为的任何格式。 5. 最后,记得在您的代码中关闭 OfficeManager 实例,以便它可以正确地停止并释放资源。以下是一个示例代码片段: ``` officeManager.stop(); ``` 希望这可以帮助您开始使用 JodConverter 远程访问 OpenOffice/LibreOffice 进行文档换。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值