首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Web不能执行soffice.exe --转换- pdf命令。

Web不能执行soffice.exe --转换- pdf命令。
EN

Stack Overflow用户
提问于 2021-08-09 08:53:17
回答 1查看 258关注 0票数 0

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

但这会给我带来一个错误:

Error: source file could not be loaded

此错误由soffice.exe进程抛出。

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

我的代码:

主计长:

代码语言:javascript
复制
[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 .Net 5
  • Libre版本: 7.1.5
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-09 10:35:38

可能是这个函数{Path.GetFileName(Path.GetFullPath(filePath))}吗?据我所知,它只返回路径如本例所述,来自微软。的文件名和扩展名。

为什么不直接使用变量filePath

编辑:我刚刚注意到你在这个过程中使用WorkingDirectory。对于其参数,Soffice可能无法使用相对路径。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68709319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档