【问题标题】:Web API cannot execute soffice.exe --convert-to pdf commandWeb API 无法执行 soffice.exe --convert-to pdf 命令
【发布时间】:2021-08-09 08:53:17
【问题描述】:

我想通过我的 API 上传一个 docx 文件,它需要返回一个由 libreoffice soffice.exe 进程转换的 pdf 文件。

但这会给我一个错误:

Error: source file could not be loaded

这个错误是soffice.exe进程抛出的。

当我尝试直接执行 soffice.exe 进程(不是通过 api 调用)时,他成功地将我的 docx 文件转换为 pdf。

我的代码:

控制器:

[HttpPost]
public IActionResult Post(IFormFile docxFile)
{
    if (docxFile == null)
    {
        return BadRequest();
    }
    
    if (docxFile.ContentType != "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
    {
        ModelState.AddModelError("message", "Wrong file type provided. Only docx file are accepted.");
        return UnprocessableEntity(ModelState);
    }

    string filePath = "C:\\temp.docx";

    using (Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
    {
        docxFile.CopyTo(stream);
    }
    
    ProcessStartInfo procStartInfo =
        new("C:\\Program\\LibreOffice\\program\\soffice.exe", $"--convert-to pdf --nologo '{Path.GetFileName(Path.GetFullPath(filePath))}'")
        {
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            WindowStyle = ProcessWindowStyle.Normal,
            CreateNoWindow = true,
            WorkingDirectory = Path.GetDirectoryName(Path.GetFullPath(filePath)) ?? string.Empty
        };

    using (Process process = new() {StartInfo = procStartInfo,})
    {
        process.OutputDataReceived += (sender, data) => Console.WriteLine(data.Data);
        process.ErrorDataReceived += (sender, data) => Console.WriteLine(data.Data);
        process.Start();
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();
        process.WaitForExit();
    }
    
    FileStream fileStream = System.IO.File.Open(filePath.Replace(".docx", ".pdf"), FileMode.Open);

    return File(fileStream, "application/octet-stream", Path.GetFileName(fileStream.Name));
    
}

特性:

  • ASP.NET Web Api .Net 5
  • Libre Office 版本:7.1.5

【问题讨论】:

  • 如果您的应用在 IIS 上运行,那么您需要确保该进程在可以访问该文件的用户帐户上运行。

标签: c# asp.net .net .net-5 libreoffice


【解决方案1】:

可能是这个函数{Path.GetFileName(Path.GetFullPath(filePath))}? 据我了解,它仅返回路径中的文件名和扩展名 as described in this example from Microsoft

你为什么不直接使用你的变量filePath

编辑: 我刚刚注意到您正在使用 WorkingDirectory 进行该过程。 Soffice 可能无法使用其参数的相对路径。

【讨论】:

  • 我忘记在我的帖子中用 filePath 替换 {Path.GetFileName(Path.GetFullPath(filePath))},我把它放在我的测试中,但我在输出中有同样的错误 > 错误: 无法加载源文件
  • 您使用的是完全相同的命令吗?喜欢: C:\\Program\\LibreOffice\\program\\soffice.exe --convert-to pdf --nologo C:\\temp.docx ?编辑:您是否尝试过在 args 开头移动 --no-logo arg?
猜你喜欢
  • 2015-08-01
  • 2022-12-02
  • 1970-01-01
  • 2020-06-19
  • 2016-08-20
  • 2020-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多