基于libreOffice的doc,docx,ppt,pptx,txt,xlsx,xls转pdf java实现

1、安装libreOffice

2、代码实现

 

package com.szoa.util.pdf;

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

import org.jodconverter.OfficeDocumentConverter;
import org.jodconverter.office.DefaultOfficeManagerBuilder;
import org.jodconverter.office.OfficeException;
import org.jodconverter.office.OfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PDFConvert {
    private static String officeHomeDir = null;

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

    /**
     * 
     *@name    文档转换为pdf工具类
     *@description 相关说明 支持:xls,xlsx,ppt,pptx,txt,其中doc,docx转换与原文件有较大差异,libreOffice 默认安装路径
     *Linux:/opt/libreoffice6.0
     *Windows:C:/Program Files (x86)/LibreOffice
     *Mac:/Application/openOfficeSoft
     *@time    创建时间:2018年9月17日下午1:49:18
     *@param sourceFile 需要转换的原文件
     *@param tarPdfFile 转换后的目标pdf文件
     *@return
     *@throws OfficeException
     *@author   myflea@163.com
     *@history 修订历史(历次修订内容、修订人、修订时间等)
     */
    public static String doDocToFdpLibre(String sourceFile, String tarPdfFile) throws OfficeException {

        File inputFile = new File(sourceFile);

        String libreOfficePath = getOfficeHome();

        DefaultOfficeManagerBuilder builder = new DefaultOfficeManagerBuilder();
        builder.setOfficeHome(new File(libreOfficePath));
        // 端口号
        builder.setPortNumber(8100);
        builder.setTaskExecutionTimeout(1000 * 60 * 5L);
        // 设置任务执行超时为5分钟
        builder.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
        // 设置任务队列超时为24小时

        OfficeManager officeManager = builder.build();
        startService(officeManager);
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        File outputFile = new File(tarPdfFile);
        converter.convert(inputFile, outputFile);
        stopService(officeManager);
        String pdfPath = outputFile.getPath();
        return pdfPath;
    }

    private static String getOfficeHome() {

        if (null != officeHomeDir) {
            return officeHomeDir;
        } else {
            String osName = System.getProperty("os.name");
            if (Pattern.matches("Windows.*", osName)) {
                officeHomeDir = "C:/Program Files (x86)/LibreOffice";
                return officeHomeDir;
            } else if (Pattern.matches("Linux.*", osName)) {
                officeHomeDir = "/opt/libreoffice6.0";
                return officeHomeDir;
            } else if (Pattern.matches("Mac.*", osName)) {
                officeHomeDir = "/Application/openOfficeSoft";
                return officeHomeDir;
            }
            return null;
        }

    }

    private static void stopService(OfficeManager officeManager) throws OfficeException {
        if (null != officeManager) {
            officeManager.stop();
        }
        logger.info("关闭office转换成功!");
    }

    private static void startService(OfficeManager officeManager) {

        try {
            // 准备启动服务
            officeManager.start(); // 启动服务
            logger.info("office转换服务启动成功");
        } catch (Exception ce) {
            logger.error("office转换服务启动失败!详细信息:{}", ce);
        }
    }

    /**
     * 
     *@name    设置libreOffice安装目录
     *@description 相关说明:如果libreOffice安装目录为默认目录,则不需要设置,否则需要设置
     *@time    创建时间:2018年9月17日下午1:52:36
     *@param officeHome
     *@author   作者
     *@history 修订历史(历次修订内容、修订人、修订时间等)
     */
    public static void setOfficeHome(String officeHome) {
        officeHomeDir = officeHome;
    }
}

3、pom.xml 依赖

<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>com.szoa</groupId>
  <artifactId>szoa-pdf-util</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <name>soze-pdf-util</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  


  <dependencies>
	<dependency> 
		  <groupId>org.slf4j</groupId>
		  <artifactId>slf4j-log4j12</artifactId>
		  <version>1.8.0-alpha2</version>
		</dependency>
	<dependency>
	  <groupId>org.jodconverter</groupId>
	  <artifactId>jodconverter-core</artifactId>
	  <version>4.0.0-RELEASE</version>
	</dependency>
  </dependencies>
   <build>
  	<finalName>szoa-pdf-util-${project.version}</finalName>
  	  <plugins>
    		<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			
			<plugin>  
			    <groupId>org.apache.maven.plugins</groupId>  
			    <artifactId>maven-assembly-plugin</artifactId>  
			    <version>2.5.5</version>  
			    <configuration>  
			        <archive>  
			            <manifest>  
			                <mainClass>com.szoa.util.pdfmain.PdfDomain</mainClass>  
			            </manifest>  
			        </archive>  
			        <descriptorRefs>  
			            <descriptorRef>jar-with-dependencies</descriptorRef>  
			        </descriptorRefs>  
			    </configuration>  
			    <executions>  
			        <execution>  
			            <id>make-assembly</id>  
			            <phase>package</phase>  
			            <goals>  
			                <goal>single</goal>  
			            </goals>  
			        </execution>  
			    </executions>  
		</plugin>	
	</plugins>
  </build>
    
</project>

4、安装libreOffice

  1. 下载 版本6.0.6windows版本

安装流程:

  1. 下载linux版本

rpm安装方式安装

tar -zxvf LibreOffice_6.0.6_Linux_x86-64_rpm.tar.gz

cd  LibreOffice_6.0.6

cd  LibreOffice_6.0.6.2_Linux_x86-64_rpm/

  cd RPMS/

rpm -ivh *.rpm

[root@bogon RPMS]#  rpm -ivh *.rpm

Preparing...                ########################################### [100%]

   1:libreoffice6.0-ure     ########################################### [  2%]

   2:libobasis6.0-core      ########################################### [  5%]

   3:libobasis6.0-base      ########################################### [  7%]

   4:libobasis6.0-impress   ########################################### [ 10%]

   5:libobasis6.0-writer    ########################################### [ 12%]

   6:libobasis6.0-calc      ########################################### [ 15%]

   7:libobasis6.0-draw      ########################################### [ 17%]

   8:libobasis6.0-en-US     ########################################### [ 20%]

   9:libobasis6.0-images    ########################################### [ 22%]

  10:libreoffice6.0         ########################################### [ 24%]

  11:libobasis6.0-math      ########################################### [ 27%]

  12:libobasis6.0-pyuno     ########################################### [ 29%]

  13:libobasis6.0-librelogo ########################################### [ 32%]

  14:libreoffice6.0-math    ########################################### [ 34%]

  15:libreoffice6.0-base    ########################################### [ 37%]

  16:libreoffice6.0-calc    ########################################### [ 39%]

  17:libreoffice6.0-dict-en ########################################### [ 41%]

  18:libreoffice6.0-dict-es ########################################### [ 44%]

  19:libreoffice6.0-dict-fr ########################################### [ 46%]

  20:libreoffice6.0-draw    ########################################### [ 49%]

  21:libreoffice6.0-en-US   ########################################### [ 51%]

  22:libreoffice6.0-impress ########################################### [ 54%]

  23:libreoffice6.0-writer  ########################################### [ 56%]

  24:libobasis6.0-ogltrans  ########################################### [ 59%]

  25:libobasis6.0-postgresql########################################### [ 61%]

  26:libobasis6.0-extension-########################################### [ 63%]

  27:libobasis6.0-extension-########################################### [ 66%]

  28:libobasis6.0-extension-########################################### [ 68%]

  29:libobasis6.0-extension-########################################### [ 71%]

  30:libobasis6.0-extension-########################################### [ 73%]

  31:libobasis6.0-extension-########################################### [ 76%]

  32:libobasis6.0-firebird  ########################################### [ 78%]

  33:libobasis6.0-gnome-inte########################################### [ 80%]

  34:libobasis6.0-graphicfil########################################### [ 83%]

  35:libobasis6.0-kde-integr########################################### [ 85%]

  36:libobasis6.0-onlineupda########################################### [ 88%]

  37:libobasis6.0-ooofonts  ########################################### [ 90%]

  38:libobasis6.0-ooolinguis########################################### [ 93%]

  39:libobasis6.0-python-scr########################################### [ 95%]

  40:libobasis6.0-xsltfilter########################################### [ 98%]

  41:libreoffice6.0-freedesk########################################### [100%]

/usr/bin/update-desktop-database

/usr/bin/update-mime-database

mkdir: 无法创建目录"/usr/share/icons/hicolor/icon-theme.cache": 不是目录

mkdir: 无法创建目录"/usr/share/icons/hicolor/index.theme": 不是目录

/usr/bin/gtk-update-icon-cache

/usr/bin/gtk-update-icon-cache

/usr/bin/update-desktop-database

/usr/bin/update-desktop-database

默认安装目录:/opt/libreoffice6.0

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用LibreOfficeJava API来实现LibreOffice文档换为PDF文档。以下是实现的步骤: 1. 首先需要确保LibreOffice已经安装在系统中,并且已经配置好了环境变量。同时需要下载并安装LibreOfficeJava API。 2. 在Java程序中引入LibreOfficeJava API所在的jar包。 3. 使用以下代码将文档换为PDF文档: ``` import com.sun.star.beans.PropertyValue; import com.sun.star.frame.XComponentLoader; import com.sun.star.lang.XComponent; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; public class ConvertToPDF { public static void main(String[] args) { XComponentContext xContext = null; try { //获取LibreOffice的上下文 xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); XComponentLoader xLoader = UnoRuntime.queryInterface(XComponentLoader.class, xContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", xContext)); //设置待换文档的路径和文件名 String fileToConvert = "file:///C:/example.docx"; //设置换后的PDF文档的路径和文件名 String pdfFile = "file:///C:/example.pdf"; //设置换参数 PropertyValue[] conversionProperties = new PropertyValue[2]; conversionProperties[0] = new PropertyValue(); conversionProperties[0].Name = "Hidden"; conversionProperties[0].Value = Boolean.TRUE; conversionProperties[1] = new PropertyValue(); conversionProperties[1].Name = "FilterName"; conversionProperties[1].Value = "writer_pdf_Export"; //打开待换文档 XComponent xComponent = xLoader.loadComponentFromURL(fileToConvert, "_blank", 0, conversionProperties); //将文档换为PDF格式 PropertyValue[] storeProperties = new PropertyValue[3]; storeProperties[0] = new PropertyValue(); storeProperties[0].Name = "FilterName"; storeProperties[0].Value = "writer_pdf_Export"; storeProperties[1] = new PropertyValue(); storeProperties[1].Name = "Overwrite"; storeProperties[1].Value = Boolean.TRUE; storeProperties[2] = new PropertyValue(); storeProperties[2].Name = "Hidden"; storeProperties[2].Value = Boolean.TRUE; UnoRuntime.queryInterface(XStorable.class, xComponent).storeToURL(pdfFile, storeProperties); //关闭文档 UnoRuntime.queryInterface(XCloseable.class, xComponent).close(Boolean.TRUE); } catch (Exception e) { e.printStackTrace(); } finally { if (xContext != null) { com.sun.star.uno.Runtime.getRuntime(xContext).freeUnusedLibraries(); } } } } ``` 4. 运行程序即可将LibreOffice文档换为PDF文档。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值