LibreOffice在ASP.NET MVC中将XLSX转换为PDF
本文关键字:XLSX 转换 PDF 中将 MVC ASP NET LibreOffice | 更新日期: 2023-09-27 18:29:43
4.3版
在C#中,我试图使用headless选项将XLSX转换为PDF,但当我从ASP.NET或简单的命令提示符运行此选项时,不会发生任何事情。
var pdfProcess = new Process();
pdfProcess.StartInfo.FileName = exe;
pdfProcess.StartInfo.Arguments = param + " '"" + fullDocPath +"'"";
pdfProcess.Start();
exe和params所在的位置:
C:'Program Files (x86)'LibreOffice 4'program'soffice.exe
-norestore -nofirststartwizard -nologo -headless -convert-to pdf "c:'UDS_Docs'temp'Teller Roster National.xlsx"
我使用GUI来测试LibreOffice是否可以转换文件,它运行得很好。
以下是如何在ASP.NET MVC网站上免费将Excel、Word等转换为PDF的方法:
安装LibreOffice,免费
将当前目录设置为与现有XLS相同的文件夹。这似乎是缺失的部分。
运行此:
"C:'Program Files (x86)'LibreOffice 4'program'soffice.exe" -norestore -nofirststartwizard -headless -convert-to pdf "TheFile.xlsx"
在C#中:
var pdfProcess = new Process();
pdfProcess.StartInfo.FileName = exePdf;
pdfProcess.StartInfo.Arguments = "-norestore -nofirststartwizard -headless -convert-to pdf '"TheFile.xlsx'"";
pdfProcess.StartInfo.WorkingDirectory = docPath; //This is really important
pdfProcess.Start();
确保WorkerProcess有权访问exe,默认情况下没有。
事实证明,我试图运行的exe需要大量访问权限(它是LibreOffice,用于从Excel制作PDF)。
因此,最简单的解决方案就是制作一个超级简单的WindowsService,安装并运行它。网站将大量数据放入服务监视的位置,然后完成工作,网站稍后再提取数据。这样,我可以在最低权限下运行网站,并且仍然可以运行主要服务。
基于@BahaiResearch.com的GREAT答案,我在转换代码中添加了一些函数:
string fileName = Path.GetFileName(excelFilePath);
string fileDir = Path.GetDirectoryName(excelFilePath);
var pdfProcess = new Process();
pdfProcess.StartInfo.FileName = @"C:'Program Files'LibreOffice'program'soffice.exe";
pdfProcess.StartInfo.Arguments =
String.Format("--norestore --nofirststartwizard --headless --convert-to pdf '"{0}'""
, fileName);
pdfProcess.StartInfo.WorkingDirectory = fileDir;
pdfProcess.StartInfo.RedirectStandardOutput = true;
pdfProcess.StartInfo.RedirectStandardError = true;
pdfProcess.StartInfo.UseShellExecute = false;
pdfProcess.Start();
string output = pdfProcess.StandardOutput.ReadToEnd();
string error = pdfProcess.StandardError.ReadToEnd();
一些参考:StandardOutput UseShellExecute