【发布时间】: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