我想通过我的API上传一个docx文件,它需要返回一个由libreoffice soffice.exe进程转换的pdf文件。
但这会给我带来一个错误:
Error: source file could not be loaded
此错误由soffice.exe进程抛出。
当我试图直接(而不是通过api调用)执行soffice.exe过程时,他成功地将我的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));
}具体情况:
发布于 2021-08-09 10:35:38
可能是这个函数{Path.GetFileName(Path.GetFullPath(filePath))}吗?据我所知,它只返回路径如本例所述,来自微软。的文件名和扩展名。
为什么不直接使用变量filePath
编辑:我刚刚注意到你在这个过程中使用WorkingDirectory。对于其参数,Soffice可能无法使用相对路径。
https://stackoverflow.com/questions/68709319
复制相似问题