使用Libreoffice实现word转pdf

本文介绍了一种使用LibreOffice将多种办公文档格式转换为PDF的方法。通过Java编程实现,支持doc、docx、xls、xlsx、ppt、pptx和txt等文件格式的转换。代码中详细展示了如何配置LibreOffice环境并进行文件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Pattern;

public class TextUtil {

private static String LIBREOFFIC_HOME_WINDOWS = "C:\\Program Files\\LibreOffice 5";
private static String LIBREOFFIC_HOME_LINUX = "/usr/bin";
public static void main(String[] args) throws IOException {
File input = new File("C:\\Users\\LQG\\Desktop\\test.xlsx");
File output = new File("C:\\Users\\LQG\\Desktop\\execl.pdf");
FileInputStream fileInputStream = new FileInputStream("C:\\Users\\LQG\\Desktop\\test.docx");
FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\LQG\\Desktop\\io.pdf");
libreOffice2PDF(fileInputStream,fileOutputStream,"docx");
}
public static String getLibreOfficeHome() {
String osName = System.getProperty("os.name");
if (Pattern.matches("Linux.*", osName)) {
     return LIBREOFFIC_HOME_LINUX;
 } else if (Pattern.matches("Windows.*", osName)) {
      return LIBREOFFIC_HOME_WINDOWS;
 }
 return null;
}
/**
* 转换libreoffice支持的文件为pdf
* @param inputfile 输入文件
* @param outputfile 输出的文件
*/
 public static void libreOffice2PDF(File inputfile, File outputfile) {
String LibreOffice_HOME = getLibreOfficeHome();
DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
// libreOffice的安装目录
if(StringUtils.isEmpty(LibreOffice_HOME)){
      throw new BaseException("libreoffice_home is not found");
}
configuration.setOfficeHome(new File(LibreOffice_HOME));
// 端口号
configuration.setPortNumber(8100);
configuration.setTaskExecutionTimeout(1000 * 60 * 25L);
//设置任务执行超时为10分钟
configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
//设置任务队列超时为24小时
OfficeManager officeManager = configuration.buildOfficeManager();
officeManager.start();
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
converter.getFormatRegistry();
try {
       converter.convert(inputfile, outputfile);
 } catch (Exception e) {
        e.printStackTrace();
  } finally {
            officeManager.stop();
  }
}
private static File txtHandler(File file) {
//或GBK
String code = "gb2312";
byte[] head = new byte[3];
try {
    InputStream inputStream = new FileInputStream(file);
    inputStream.read(head);
    if (head[0] == -1 && head[1] == -2) {
         code = "UTF-16";
    } else if (head[0] == -2 && head[1] == -1) {
         code = "Unicode";
    } else if (head[0] == -17 && head[1] == -69 && head[2] == -65) {
        code = "UTF-8";
    }
   inputStream.close();


   System.out.println(code);
   if (code.equals("UTF-8")) {
          return file;
   }
   String str = FileUtils.readFileToString(file, code);
   FileUtils.writeStringToFile(file, str, "UTF-8");
   System.out.println("转码结束");
} catch (FileNotFoundException e) {
      e.printStackTrace();
 } catch (IOException e) {
      e.printStackTrace();
}
        return file;
}


/**
* office文件转pdf
* @param fileInputStream 输入流
* @param fileOutputStream 输出流
* @param fileExt 文件后缀 doc,docx,xls,xlsx,ppt,pptx,txt
*/

public static void libreOffice2PDF(FileInputStream fileInputStream, 

                                                                FileOutputStream fileOutputStream,

                                                                String fileExt) throws IOException {

if(StringUtils.isEmpty(fileExt)){
       throw new BaseException("error.fileExt" + fileExt);
 }
 File inputFile = null;
 switch (fileExt){
            case "doc":
                inputFile = new File("src/main/resources/tempFile/tempDoc.doc");
                break;
            case "docx":
                inputFile = new File("src/main/resources/tempFile/tempDocx.docx");
                break;
            case "xls":
                inputFile = new File("src/main/resources/tempFile/tempXls.xls");
                break;
            case "xlsx":
                inputFile = new File("src/main/resources/tempFile/tempXlss.xlsx");
                break;
            case "ppt":
                inputFile = new File("src/main/resources/tempFile/tempPpt.ppt");
                break;
            case "pptx":
                inputFile = new File("src/main/resources/tempFile/tempPptx.pptx");
                break;
            case "txt":
                inputFile = new File("src/main/resources/tempFile/tempTxt.txt");
                txtHandler(inputFile);
                break;
            default:
                throw new BaseException("error.fileExt" + fileExt);
        }
        byte[] byteArr = IOUtils.toByteArray(fileInputStream);
        FileUtils.writeByteArrayToFile(inputFile,byteArr);


        File outFile = new File("/tempFile/tempPdf.pdf");
        libreOffice2PDF(inputFile,outFile);
        byte[] bytes = FileUtils.readFileToByteArray(outFile);
        fileOutputStream.write(bytes);
    }

}


上述代码为实现libreoffice转pdf的操作代码,完整的文档请看https://download.youkuaiyun.com/download/lvguoqiangm/10324036

Node.js 是一种在服务器端运行的 JavaScript 运行环境,可以用于实现各种各样的应用程序。而 LibreOffice 是一款免费、开源的办公软件套件,其中包括了 Writer、Calc、Impress 等应用程序,支持多种文档格式。下面是一个基于 Node.js 和 LibreOffice实现 Word PDF 的简单方法: 1.安装 LibreOffice:首先需要在服务器上安装 LibreOffice,可以通过命令行或者图形界面进行安装。 2.使用 Node.js 的 child_process 模块:在 Node.js 中可以通过 child_process 模块来执行系统命令,在本例中可以使用该模块执行 LibreOffice命令行工具来进行 Word PDF 的操作。 3.编写 Node.js 代码:可以通过 Node.js 编写一个简单的脚本来实现 Word PDF。以下是一个简单的示例代码: ```javascript const { spawn } = require('child_process'); const inputFilePath = '/path/to/input.docx'; const outputFilePath = '/path/to/output.pdf'; const libreoffice = spawn('libreoffice', [ '--headless', '--convert-to', 'pdf', inputFilePath, '--outdir', outputFilePath, ]); libreoffice.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); libreoffice.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); libreoffice.on('close', (code) => { console.log(`child process exited with code ${code}`); }); ``` 以上代码中,spawn 方法会启动一个新的进程来执行 LibreOffice 命令行工具。'--headless' 参数表示以无头模式运行,'--convert-to pdf' 参数表示换成 PDF 格式,inputFilePath 参数表示输入文件的路径,'--outdir' 参数表示输出文件的路径。 4.运行 Node.js 代码:在终端中运行 Node.js 脚本即可进行 Word PDF 的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值