windows及linux环境:libreoffice实现word转pdf

1.CentOS安装 LiberOffice

1.1 在线安装LiberOffice

yum install -y libreoffice

1.2查看版本号

libreoffice --version

在这里插入图片描述

1.3 查看软连接

which libreoffice

在这里插入图片描述

ll /usr/bin/ |grep libre

在这里插入图片描述
由输出结果可以看出,soffice指向了/usr/lib64/libreoffice/program/soffice路径,所以下面执行启动命令的时候直接用soffice执行就可以。

1.4启动LibreOffice

soffice --headless --accept="socket,host=0.0.0.0,port=8100;urp;" --nofirststartwizard &

在这里插入图片描述

1.5 查看是否启动成功

ps -ef|grep libreoffice

在这里插入图片描述

1.6 安装字库

yum -y install fontconfig

yum -y install ttmkfdir

执行成功后,/usr/share目录下会有fonts和fontconfig文件夹。
在这里插入图片描述
在/usr/share/fonts下创建chinese文件夹,并给chinese目录赋权限。

cd /usr/share/fonts
mkdir chinese
chmod 777 chinese

我们到自己的windows电脑上查找想要的字体,访问C:\Windows\Fonts,选择自己想要上传的字体,上传到chinese目录下。
在这里插入图片描述

在这里插入图片描述
执行以下命令,生成 TrueType 字体的字体度量

ttmkfdir -e /usr/share/X11/fonts/encodings/encodings.dir

编辑字体配置文件,配置刚才创建中文字体目录。

vi /etc/fonts/fonts.conf

在这里插入图片描述
执行命令,刷新字体缓存

fc-cache

2. Java代码实现word转pdf

2.1 maven依赖

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

2.2 代码片段

/**
* word转换为pdf
* @param currentTimeMillis 当前时间时间戳
* @param outDocxPath 输出的word路径
* @return
*/
private String wordConvertToPDF(Long currentTimeMillis,String outDocxPath){
        //转换后的pdf文件路径
        String outFileName = currentTimeMillis+".pdf";
        String pdfPath = DtapConfig.getOutPath()+ outFileName;
        File inputWord = new File(outDocxPath);
        File outputFile = new File(pdfPath);

        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")){
            //windows系统
            try {
                InputStream docxInputStream = new FileInputStream(inputWord);
                OutputStream outputStream = new FileOutputStream(outputFile);
                IConverter converter = com.documents4j.job.LocalConverter.builder().build();

                if (outDocxPath.split("\\.")[1].equals("doc")) {
                    converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
                } else {
                    converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
                }
                outputStream.close();
                docxInputStream.close();
                return pdfPath;
            } catch (Exception e) {
                System.out.println("PDF转换失败");
                return null;
            }
        }else if(os.contains("nix") || os.contains("nux") || os.contains("mac")){
            // Unix/Linux/Mac操作系统
            // 获取源文件的绝对路径和目录路径
            String absolutePath = inputWord.getAbsolutePath();
            String parentPath = inputWord.getParent();

            // 构建LibreOffice的命令行工具命令
            String commands = "soffice --headless --convert-to pdf "
                    + absolutePath + " --outdir " + parentPath;
            // 执行转换命令
            try {
                // 执行命令行工具命令
                Process process = Runtime.getRuntime().exec(commands);
                process.waitFor();
                    // 转换成功,返回转换后的PDF文件
                    return pdfPath ;
            }catch (Exception e){
                System.out.println("==================转换失败==================");
                e.printStackTrace();

            }


        }else {
            // 未知操作系统
            throw new RuntimeException("不支持当前操作系统转换文档");
        }
        return null;

    }
### .NET在Linux环境下通过LibreOffice实现PPT到PDF换 虽然JODConverter主要用于Java环境下的文件格式换[^1],但在.NET环境中也可以借助LibreOffice的服务来完成类似的换操作。具体来说,在Linux下可以通过调用LibreOffice命令行工具`soffice`来执行PPT到PDF换。 以下是基于.NET Core的一个简单方法: #### 使用System.Diagnostics.Process启动LibreOffice进程 可以在C#程序中利用`Process`类运行外部命令,从而间接调用LibreOffice进行文件换。下面是一段示例代码用于演示如何将PPT文件换成PDF文件: ```csharp using System; using System.Diagnostics; public class PptToPdfConverter { public static void Convert(string inputFile, string outputFile) { var processStartInfo = new ProcessStartInfo { FileName = "libreoffice", // 调用 LibreOffice 的 soffice 命令 Arguments = $"--headless --convert-to pdf:writer_pdf_Export \"{inputFile}\" --outdir {Path.GetDirectoryName(outputFile)}", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; using (var process = new Process()) { process.StartInfo = processStartInfo; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) throw new Exception($"Conversion failed with exit code {process.ExitCode}"); } } public static void Main() { try { string inputFilePath = "/path/to/input.ppt"; // 输入的PPT文件路径 string outputFilePath = "/path/to/output.pdf"; // 输出的PDF文件路径 Convert(inputFilePath, outputFilePath); Console.WriteLine("Conversion completed successfully."); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } } ``` 上述代码片段展示了如何使用LibreOffice命令行参数`--headless`, `--convert-to`, 和`--outdir`选项来静默模式下批量处理文件并指定输出目录[^2]。 需要注意的是: - 确保已安装最新版本的LibreOffice,并且可以从终端正常访问其可执行文件(通常名为`libreoffice`或`soffice`)。 - 如果目标服务器上未预装图形界面,则需确认该无头模式(`--headless`)能够顺利工作。 此外,对于更复杂的场景比如自定义样式或是高级功能支持时,可能还需要探索其他库或者API接口作为补充解决方案。 #### 可能遇到的问题及解决办法 如果发现某些特定情况下无法成功换,请考虑以下几点建议: 1. **字体缺失**:检查源文档使用的字体是否存在于当前操作系统配置当中; 2. **权限不足**:验证应用程序是否有足够的权限读取输入文件以及写入输出位置; 3. **兼容性问题**:尝试更新至最新的LibreOffice发行版以获得更好的稳定性与特性改进;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值