LibreOffice转PDF报错:文件或目录不存在问题求助
ODT转PDF调用LibreOffice报错“No such file or directory”及无输出问题解决
问题背景
以root用户执行C#代码调用LibreOffice转换ODT到PDF时,日志报错“No such file or directory”,排查发现代码中指定的LibreOffice路径/usr/lib/libreoffice/program/soffice不存在;改用bash+sudo调用后无报错,但始终未生成PDF文件。
解决方案步骤
1. 确认LibreOffice的实际安装路径
先通过命令行找到系统中soffice的真实位置:
# 方法一:查找可执行文件路径 which soffice # 方法二:全局搜索 find / -name soffice -type f
常见的有效路径包括/usr/bin/soffice或/opt/libreoffice/program/soffice,找到后替换代码中的progPath值。
2. 修复直接调用的代码(推荐)
因为当前运行用户已是root,无需sudo,直接修正路径并添加错误输出排查:
fileName = Path.Combine(Path.GetTempPath(), string.Concat(name, ".odt")); using(FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) { inputStream.Position = 0; inputStream.CopyTo(fs); // using块会自动关闭流,无需手动调用fs.Close() } // 替换为实际找到的soffice路径 progPath = @"/usr/bin/soffice"; var outDir = Path.GetDirectoryName(fileName); // 用字符串插值简化参数,避免引号转义问题 var args = $"--headless --convert-to pdf:writer_pdf_Export --outdir \"{outDir}\" \"{fileName}\""; psi = new ProcessStartInfo { FileName = progPath, Arguments = args, // 开启错误输出重定向,方便排查执行问题 RedirectStandardError = true, UseShellExecute = false }; using(var p = Process.Start(psi)) { if(p != null) { // 读取错误信息,用于调试 string errorMsg = p.StandardError.ReadToEnd(); p.WaitForExit(); // 打印错误日志,定位问题 Console.WriteLine("LibreOffice执行错误:" + errorMsg); } }
3. 排查sudo调用无输出的问题(若必须使用)
如果业务场景要求用sudo调用,需解决引号嵌套和环境变量问题:
progPath = @"/usr/bin/soffice"; // 替换为实际路径 var outDir = Path.GetDirectoryName(fileName); var args = $"--headless --convert-to pdf:writer_pdf_Export --outdir \"{outDir}\" \"{fileName}\""; // 转义参数中的引号,避免bash解析错误 var escapedArgs = args.Replace("\"", "\\\""); var bashCommand = $"-c 'sudo {progPath} {escapedArgs}'"; psi = new ProcessStartInfo { FileName = "/bin/bash", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, Arguments = bashCommand }; using(var p = Process.Start(psi)) { if(p != null) { string output = p.StandardOutput.ReadToEnd(); string error = p.StandardError.ReadToEnd(); p.WaitForExit(); // 打印输出和错误信息 Console.WriteLine("输出:" + output); Console.WriteLine("错误:" + error); } }
4. 额外排查点
- 验证ODT文件完整性:打开临时目录下的ODT文件,确认文件未损坏、内容完整
- 检查LibreOffice可用性:执行
soffice --version,确认程序能正常启动 - 确认输出目录权限:确保临时目录(
Path.GetTempPath())有写入权限(root用户默认具备)
内容的提问来源于stack exchange,提问作者Алексей Корсак
相关产品推荐
相关产品推荐

