使用Libreoffice(Windows版)将office文档(word,ppt,excel)转pdf

Windows下使用LibreOffice将office文档(word,ppt,excel)转成PDF(Java)
第一步:安装Windows版LibreOffice
1.1去官网LibreOffice

https://zh-cn.libreoffice.org/

1.2下载

在这里插入图片描述

1.2.1第一步:进入官网点击下载

在这里插入图片描述

1.2.2第二步:选择合适自己系统的版本

在这里插入图片描述

1.2.2第三步:点击红色框里面的进行下载

在这里插入图片描述

1.3安装以及配置
1.3.1第一步:双击下载好的文件

在这里插入图片描述

1.3.2第二步:点击下一步

在这里插入图片描述

1.3.3第三步:这里选择自定义

在这里插入图片描述

1.3.4第四步:这里可以使用默认路劲或者自己选择安装路劲

在这里插入图片描述

1.3.5第五步:点击下一步

在这里插入图片描述

1.3.6第六步:点击安装

在这里插入图片描述

1.3.7第七步:windows10的话找到此电脑=>鼠标右击选择属性=>高级系统设置=>环境变量=>找到系统环境变量path新建添加D:\LibreOffice\program路径(注意此路径是根据自己安装的路劲配置的我的是安装在D盘下)

在这里插入图片描述

1.3.8第八步然后windows+R打开cmd命令窗口=>输入soffice打开了LibreOffice则表示安装成功

在这里插入图片描述

第二步:使用java代码操作LibreOffice进行(doc,ppt,xls)文件转换成PDF文件
1.1:打开IDEA或者eclipse创建一个SpringBoot项目

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>org.example</groupId>
    <artifactId>filepreview</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
    </parent>
    <dependencies>
        <!--Springmvc启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.liumapp.workable.converter</groupId>
            <artifactId>workable-converter</artifactId>
            <version>v1.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
1.2创建一个类ConvertOfficePDFUtils.java这个文件名称自己取
/**
 * @description libreoffice工具类
 * @author holle
 * @create 2020/12/24
 * @since 1.0.0
 */
package com.file.preview.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
@Service
public class ConvertOfficePDFUtils {

    private static Logger logger=LoggerFactory.getLogger(ConvertOfficePDFUtils.class);

    /**
     * 利用libreOffice将office文档转换成pdf
     * @param inputFile  目标文件地址
     * @param pdfFile    输出文件夹
     * @return
     */
    public static boolean convertOfficePDF(String inputFile,String pdfFile){
        long start=System.currentTimeMillis();
        String command;
        boolean flag;
        String osName=System.getProperty("os.name");
        if (osName.contains("Windows")){
            command="cmd /c start soffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;
        }else {
            command="libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;
        }
        flag =executeLibreOfficeCommand(command);
        long end =System.currentTimeMillis();
        logger.debug("用时:{} ms", end - start);
        return flag;
    }

    /**
     * 执行command指令
     * @param command
     * @return
     */
    public static boolean executeLibreOfficeCommand(String command) {
        logger.info("开始进行转化.......");
        Process process;// Process可以控制该子进程的执行或获取该子进程的信息
        try {
            logger.debug("convertOffice2PDF cmd : {}", command);
            process = Runtime.getRuntime().exec(command);// exec()方法指示Java虚拟机创建一个子进程执行指定的可执行程序,并返回与该子进程对应的Process对象实例。
            // 下面两个可以获取输入输出流
            InputStream errorStream = process.getErrorStream();
            InputStream inputStream = process.getInputStream();
        } catch (IOException e) {
            logger.error(" convertOffice2PDF {} error", command,  e);
            return false;
        }
        int exitStatus = 0;
        try {
            exitStatus = process.waitFor();// 等待子进程完成再往下执行,返回值是子线程执行完毕的返回值,返回0表示正常结束
            // 第二种接受返回值的方法
            int i = process.exitValue(); // 接收执行完毕的返回值
            logger.debug("i----" + i);
        } catch (InterruptedException e) {
            logger.error("InterruptedException  convertOffice2PDF {}", command, e);
            return false;
        }
        if (exitStatus != 0) {
            logger.error("convertOffice2PDF cmd exitStatus {}", exitStatus);
        } else {
            logger.debug("convertOffice2PDF cmd exitStatus {}", exitStatus);
        }
        process.destroy(); // 销毁子进程
        logger.info("转化结束.......");
        return true;
    }
}
1.3创建一个测试类
/**
 * @description 测试类
 * @author holle
 * @create 2020/12/24
 * @since 1.0.0
 */
package com.test;

import com.file.preview.FilePreviewApplication;
import com.file.preview.utils.ConvertOfficePDFUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.io.IOException;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = FilePreviewApplication.class)
public class TestOffice {
    @Resource
    private ConvertOfficePDFUtils convertOfficePDFUtils;
    @Test
    public void JunintTestPDF(){
        long start =System.currentTimeMillis();
        String srcPath ="C:/Users/holler/Desktop/*/*.docx",desPath="C:/Users/holler/Desktop/*";
        String command="";
        String osName=System.getProperty("os.name");
        if (osName.contains("Windows")){
            //输入cmd命令;添加:srcPath表示文件所在路径;desPath:文件输出的路径
            command="soffice --headless --convert-to pdf " + srcPath + " --outdir " + desPath;
            convertOfficePDFUtils.executeLibreOfficeCommand(command);
        }
        long end=System.currentTimeMillis();
        System.out.println("用时:{} ms"+(end-start));
    }
 }   

Path + " --outdir " + desPath;
convertOfficePDFUtils.executeLibreOfficeCommand(command);
}
long end=System.currentTimeMillis();
System.out.println(“用时:{} ms”+(end-start));
}
}

可以使用Java中的Uno API来实现LibreOfficeOffice文档换为PDF的功能。具体实现步骤如下: 1. 首先需要安装LibreOffice,并启动LibreOffice服务。启动命令为: ``` soffice --headless --accept="socket,host=127.0.0.1,port=8100;urp;" ``` 2. 在Java使用Uno API连接LibreOffice服务,代码示例如下: ``` XComponentContext xContext = Bootstrap.bootstrap(); XMultiComponentFactory xMCF = xContext.getServiceManager(); Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext); XComponentLoader xCompLoader = UnoRuntime.queryInterface(XComponentLoader.class, oDesktop); ``` 3. 加载需要换的Office文档,代码示例如下: ``` String inputUrl = "file:///path/to/input.docx"; PropertyValue[] loadProps = new PropertyValue[1]; loadProps[0] = new PropertyValue(); loadProps[0].Name = "Hidden"; loadProps[0].Value = Boolean.TRUE; XComponent xDoc = xCompLoader.loadComponentFromURL(inputUrl, "_blank", 0, loadProps); ``` 4. 将文档换为PDF格式,代码示例如下: ``` String outputUrl = "file:///path/to/output.pdf"; PropertyValue[] convertProps = new PropertyValue[2]; convertProps[0] = new PropertyValue(); convertProps[0].Name = "FilterName"; convertProps[0].Value = "writer_pdf_Export"; convertProps[1] = new PropertyValue(); convertProps[1].Name = "Overwrite"; convertProps[1].Value = Boolean.TRUE; XStorable xStore = UnoRuntime.queryInterface(XStorable.class, xDoc); xStore.storeToURL(outputUrl, convertProps); ``` 5. 最后需要关闭文档LibreOffice服务,代码示例如下: ``` xDoc.dispose(); System.exit(0); ``` 完整的代码示例如下: ``` import com.sun.star.comp.helper.Bootstrap; import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XStorable; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; import com.sun.star.beans.PropertyValue; public class OfficeToPdfConverter { public static void main(String[] args) { try { // Connect to LibreOffice service XComponentContext xContext = Bootstrap.bootstrap(); XMultiComponentFactory xMCF = xContext.getServiceManager(); Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext); XComponentLoader xCompLoader = UnoRuntime.queryInterface(XComponentLoader.class, oDesktop); // Load input document String inputUrl = "file:///path/to/input.docx"; PropertyValue[] loadProps = new PropertyValue[1]; loadProps[0] = new PropertyValue(); loadProps[0].Name = "Hidden"; loadProps[0].Value = Boolean.TRUE; XComponent xDoc = xCompLoader.loadComponentFromURL(inputUrl, "_blank", 0, loadProps); // Convert document to PDF String outputUrl = "file:///path/to/output.pdf"; PropertyValue[] convertProps = new PropertyValue[2]; convertProps[0] = new PropertyValue(); convertProps[0].Name = "FilterName"; convertProps[0].Value = "writer_pdf_Export"; convertProps[1] = new PropertyValue(); convertProps[1].Name = "Overwrite"; convertProps[1].Value = Boolean.TRUE; XStorable xStore = UnoRuntime.queryInterface(XStorable.class, xDoc); xStore.storeToURL(outputUrl, convertProps); // Close document and exit xDoc.dispose(); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } } ``` 需要注意的是,在使用Uno API连接LibreOffice服务时,需要在classpath中加入相应的jar包。具体jar包名称和路径可以参考LibreOffice的安装目录。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

great-sword

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值