是否有任何免费库可以将 doc 转换为 pdf,而无需在 c# 环境中使用 Microsoft.Office.Interop.Word

abr*_*hum 1 c# pdf itext

我遇到了一个关于如何在不使用 Microsoft.Office.Interop.Word 的情况下使用 c# 将 doc 转换为 pdf 的问题。我尝试过一些第三方解决方案,例如 spire.Doc,但它们不是免费的,而且我还在 nuget 中找到了 DocX_Doc,但似乎没有关于此的教程。有没有人知道这个问题的免费解决方案,或任何说明关于 DocX_Doc。非常感谢。

sal*_*eem 5

您可以在 apache 2.0 https://www.libreoffice.org/下使用 libreOffice 是免费许可证 我已经测试过它并且它完美地工作,您只需要下载 soffice.exe 文件以转换为 pdf 您也可以将 docx 转换为图像和其他类型。

这是我测试过的示例代码:

    static string getLibreOfficePath()
    {
        switch (Environment.OSVersion.Platform)
        {
            case PlatformID.Unix:
                return "/usr/bin/soffice";
            case PlatformID.Win32NT:
                string binaryDirectory = 
          System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                return @"C:\Program Files\LibreOffice\program\soffice.exe";
            default:
                throw new PlatformNotSupportedException("Your OS is not supported");
        }
    }

    static void Main(string[] args)
    {
        string libreOfficePath = getLibreOfficePath();

        ProcessStartInfo procStartInfo = new ProcessStartInfo(libreOfficePath, 
        string.Format("--convert-to pdf C:\\test.docx")); //test.docx => input path
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        procStartInfo.CreateNoWindow = true;
        procStartInfo.WorkingDirectory = Environment.CurrentDirectory;

        Process process = new Process() { StartInfo = procStartInfo, };
        process.Start();
        process.WaitForExit();

        // Check for failed exit code.
        if (process.ExitCode != 0)
        {
            throw new LibreOfficeFailedException(process.ExitCode);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我希望它对你有帮助。谢谢。