首页 文章

LibreOffice在ASP.NET MVC中将XLSX转换为PDF

提问于
浏览
3

版本4.3

在C#中,我试图使用无头选项将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可以转换文件,它运行正常 .

3 回答

  • 6

    以下是如何在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,默认情况下不会 .

  • 2

    事实证明,我试图运行的exe需要大量访问权限(它是LibreOffice,用于从Excel制作PDF) .

    所以最简单的解决方案就是制作一个超级简单的WindowsService,安装它并运行它 . 该网站将大量数据丢弃到服务所监视的位置,然后完成工作,网站将在以后进行处理 . 这样我就可以以最低权限运行网站,并且仍然可以运行主要服务 .

  • 1

    基于@ 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

相关问题