当前位置: 首页 > news >正文

Java通过documents4j和libreoffice把word转为pdf

文章目录

    • word转pdf的相关第三方jar说明
    • Linux系统安装LibreOffice
      • 在线安装
      • 离线安装
      • word转pdf验证
    • Java工具类代码

word转pdf的相关第三方jar说明

  • docx4j
    免费开源、稍微复杂点的word,样式完全乱了,且xalan升级为2.7.3后会报错。
  • poi
    免费开源、官方文档少、学习成本大、使用复杂、生成的样式也有问题。
  • aspire.doc
    样式保留很好、使用方便。
    未付费时,第一行会有红色水印且超过500个段落(大概25页)会被截取。
    网上没有破解版。
  • aspose.words
    样式保留很好、使用方便。
    网上有破解版。
  • documents4j
    样式保留很好、使用方便。
    底层直接调用微软的office所以,完美保留样式

Linux系统安装LibreOffice

在线安装

CentOS:使用以下命令安装

sudo yum install libreoffice

Ubuntu:使用以下命令安装

sudo apt-get install libreoffice

执行命令需要root权限:sudo -i、su

离线安装

在linux下离线安装libreoffice

word转pdf验证

查看版本:

libreoffice --version

启动服务:

nohup libreoffice --headless --accept="socket,host=127.0.0.1,port=8100;urp;" --nofirststartwizard &

word转pdf验证:

// 安装完后进入/usr/bin 或者 usr/local/bin目录下执行。 outdir输出是一个文件夹
libreoffice --headless --invisible --convert-to pdf /file/word/test.docx --outdir /file/word/test

也可以安装Apache OpenOffice,二者基本差不多,更推荐LibreOffice
LibreOffice vs OpenOffice:哪个免费办公套件更适合你?

Java工具类代码

maven依赖:

<!--word转pdf-->
<dependency><groupId>com.documents4j</groupId><artifactId>documents4j-local</artifactId><version>${documents4j.version}</version>
</dependency>
<dependency><groupId>com.documents4j</groupId><artifactId>documents4j-transformer-msoffice-word</artifactId><version>${documents4j.version}</version>
</dependency>

java代码:

package com.chinamobile.cmss.services.main.util;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;/*** Documents4j工具类** @author liquanhong* @createTime 2023/12/05*/
@Slf4j
public class Documents4jUtil {// windows 生成目录private static String winDirUrl = "D:\\temp\\file\\pdf\\";/*** word转pdf** @param file word源文件*/public static void convertWordToPdf(File file) {String os = System.getProperty("os.name").toLowerCase();log.info("convertWordToPdf 当前操作系统:{}", os);if (os.contains("win")) {// Windows操作系统windowsWordToPdf(file);} else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {// Unix/Linux/Mac操作系统linuxWordToPdf(file);} else {// 未知操作系统throw new RuntimeException("不支持当前操作系统转换文档。");}}/*** 通过documents4j 实现word转pdf -- Windows 环境 需要有 Microsoft Office 服务** @param file 源文件*/public static void windowsWordToPdf(File file) {File outputFile = new File(winDirUrl + file.getName().replaceAll("\\.(docx?|\\w+)$", "") + ".pdf");try(InputStream  docxInputStream = new FileInputStream(file);OutputStream outputStream = new FileOutputStream(outputFile)){IConverter converter = LocalConverter.builder().build();converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();} catch (Exception e) {log.error("winWordToPdf windows环境word转换为pdf时出现异常:", e);}}/*** 通过libreoffice 实现word转pdf -- linux 环境 需要有 libreoffice 服务** @param file 源文件*/public static void linuxWordToPdf(File file) {// 获取文件的绝对路径和目标路径String absolutePath = file.getAbsolutePath();String parentPath = file.getParent();// 构建LibreOffice的命令行工具命令String command = "libreoffice --headless --invisible --convert-to pdf " + absolutePath + " --outdir " + parentPath;// 执行转换命令try {executeLinuxCmd(command);} catch (Exception e) {log.error("linuxWordToPdf linux环境word转换为pdf时出现异常:", e);}}/*** 执行命令行** @param cmd 命令行* @return* @throws IOException*/private static boolean executeLinuxCmd(String cmd) throws IOException {Process process = Runtime.getRuntime().exec(cmd);try {process.waitFor();} catch (InterruptedException e) {log.error("executeLinuxCmd 执行Linux命令异常:", e);Thread.currentThread().interrupt();return false;}return true;}
}

命令行注意加上 --headless --invisible 否则异步执行的时候容易出现无反应的情况。

参考链接、参考链接、参考链接

http://www.lryc.cn/news/260015.html

相关文章:

  • 物联网时代的访问控制研究综述
  • 【产品经理】需求池和版本树
  • Qt图像处理-OpenCv中Mat与QImage互转
  • 构建外卖小程序:技术代码实践
  • IDEA中显示方法、类注释信息
  • 《数据结构、算法与应用C++语言描述》- 堆排序 - 借助priority_queue的C++实现
  • 10.CSS浮动
  • Angular 2 学习笔记
  • xcode 修改 target 中设备朝向崩溃
  • ZLMediaKit 编译以及测试(Centos 7.9 环境)
  • 汽车清除积碳和清洗节气门
  • RocketMQ 总体概括
  • 使用qemu在arm上模拟x86并运行docker
  • IIS配置多域名跨域
  • el-form表单校验输入框值为0时 提示校验不通过
  • Vue3后台管理-项目总结
  • 利用Pytorch预训练模型进行图像分类
  • MSF学习
  • Mybatis与Spring结合深探——MapperFactoryBean的奥秘
  • processon使用及流程图和泳道图的绘画(登录界面流程图,门诊流程图绘制门诊泳道图,住院泳道图,OA会议泳道图),Axure自定义元件
  • 【虹科干货】关于JSON数据库
  • 区块链的可拓展性研究【03】扩容整理
  • golang学习笔记——互斥锁sync.Mutex、计数器sync.WaitGroup、读写锁sync.RWMutex
  • MFC 加载本地文件设置图标
  • 飞天使-linux操作的一些技巧与知识点6-ansible结合jinja2使用,可规范化进行自动化管控
  • ROS2 Control分析讲解
  • Java TCP(一对一)聊天简易版
  • 2.4 C语言之运算符
  • 做题笔记:SQL Sever 方式做牛客SQL的题目--SQL157
  • 微信小程序map视野发生改变时切换定位点