使用C#将Word文件(.docx和.doc)转换为PDF无法正常工作

3

我正在使用Visual Studio 2010,尝试将word.docx文件转换为.pdf文件。在本地环境下工作正常,但在服务器运行时出现错误:

Could not load file or assembly 'office, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. The system cannot find the file specified.

我尝试过添加引用并将其放在bin文件夹中。
Microsoft.Office.Interop.Word.dll
Microsoft.Office.Interop.Word.xml

如图所示

在此输入图片描述

我的.cs代码如下:

Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

 wordApp.Visible = false;

            // file from
 object filename =Server.MapPath("word.docx"); // input

    // file to
 object newFileName = Server.MapPath("pdf/document_to_read_tomorrow.pdf"); // output
 object missing = System.Type.Missing;

            // open document
 Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing);

            // formt to save the file, this case PDF
 object formatoArquivo = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;

            // changes in paper size

 doc.PageSetup.PaperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4;

            // changes orietation paper
 doc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;

            // other changes
 doc.PageSetup.LeftMargin = 20;
 doc.PageSetup.RightMargin = 0;


            // save file
 doc.SaveAs(ref newFileName, ref formatoArquivo, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

 doc.Close(ref missing, ref missing, ref missing);

 wordApp.Quit(ref missing, ref missing, ref missing);

我的WebConfig看起来像这样:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
    <add name="xyz" connectionString="Data Source=xyz;Initial Catalog=xyz;Persist Security Info=True;User ID=xyz;Password=xyz" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
    <httpHandlers>
        <add verb="GET" path="CaptchaImage.axd" type="MSCaptcha.CaptchaImageHandler, MSCaptcha"/>
        <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false"/>
    </httpHandlers>
    <compilation debug="true" targetFramework="4.0">
        <assemblies>
            <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
            <add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
            <add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
            <add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
            <add assembly="Microsoft.Office.Interop.Word, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C"/></assemblies>
        <buildProviders>
            <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
        </buildProviders>
    </compilation>
    <customErrors mode="Off">
    </customErrors>
    <sessionState timeout="720">
    </sessionState>
    <pages enableViewStateMac="false"/>
</system.web>
<system.webServer>
    <defaultDocument>
        <files>
            <clear/>
            <add value="default.aspx"/>
        </files>
    </defaultDocument>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
        <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    </handlers>
</system.webServer>
</configuration>
4个回答

2

我的应用程序不需要安全性,也没有速度问题,我只是希望工作可以免费完成,抱歉,这是我的客户的要求。 - Mitesh Jain
@MiteshJain 客户是否为每个用户购买了一个Office许可证?如果没有,您就不能使用Office互操作性,这就是故事的结局。 - Panagiotis Kanavos

2

我长期以来一直在寻找解决这些问题的方法,最终我不得不使用第三方工具。我建议您使用像Aspose这样的第三方工具。 Aspose.Total for .NET

Aspose.Words for .NET是一个高级的.NET类库,可以让您在.NET应用程序中直接执行各种文档处理任务。

使用Aspose.Words,您可以生成、修改、转换、呈现和打印文档,而无需使用Microsoft Word。

Aspose.Words for .NET支持DOC、OOXML、RTF、HTML、OpenDocument、PDF、XPS、EPUB等多种格式。

这个组件对我来说完美地工作,并且非常容易使用。以下是将Word转换为PDF的示例代码:

Document doc = new Document(getMyDir() + "Document.doc");
doc.save(getMyDir() + "Document.Doc2PdfSave Out.pdf");

0
现在你可以很容易地使用LibreOffice在.NET Core中使用C#来完成这个任务。这里有一个关于它的小型介绍和一个指向一个可工作的自包含解决方案的链接;但是下面是代码。
using System.Diagnostics;

namespace ConvertDOCXToPDF
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create LibreOfficeWriter CLI process
            var commandArgs = new List<string>
            {
                "--convert-to", //a flag that will be followed by the file type we want to convert to
                "pdf:writer_pdf_Export", // the [output file type]:[OutputFilterName] we are requesting the output to be; more details are here (https://help.libreoffice.org/latest/en-US/text/shared/guide/convertfilters.html)
                "C:\\Users\\zachary\\Downloads\\Letter.docx", // input file
                "--norestore", // disables restart and file recovery after a system crash
                "--headless", // allows using the application without user interface
                "--outdir", // a flag that will be followed by the output directory where we want our new pdf file to be created
                "C:\\Users\\zachary\\Downloads" // output directory
            };

            // The path to LibreOfficeWriterPortable.exe
            ProcessStartInfo processStartInfo = new ProcessStartInfo("C:\\Users\\zachary\\Downloads\\LibreOfficePortablePrevious\\LibreOfficeWriterPortable.exe"); 
            foreach (string arg in commandArgs)
                processStartInfo.ArgumentList.Add(arg);

            Process process = new Process
            {
                StartInfo = processStartInfo
            };

            // Only 1 instance of LibreOfficeWriter can be running at a given time
            Process[] existingProcesses = Process.GetProcessesByName("soffice");
            while (existingProcesses.Length > 0)
            {
                Thread.Sleep(1000);
                existingProcesses = Process.GetProcessesByName("soffice");
            }

            // Start the process
            process.Start();
            process.WaitForExit();

            // Check for failed exit code.
            if (process.ExitCode != 0)
                throw new Exception("Failed to convert file");
            else
            {
                int totalChecks = 10;
                int currentCheck = 1;

                string originalFileName = Path.GetFileNameWithoutExtension(commandArgs[2]);
                string newFilePath = Path.Combine(commandArgs[6], $"{originalFileName}.pdf");

                while (currentCheck <= totalChecks)
                {
                    if (File.Exists(newFilePath))
                    {
                        // File conversion was successful

                        break;
                    }

                    Thread.Sleep(500); // LibreOffice doesn't immediately create PDF output once the command is run
                }
            }
        }
    }
}

0

您需要在服务器上的全局程序集缓存中安装“office.dll”库才能使其正常工作。请查看C:\ Windows \ assembly文件夹,您会在那里找到office.dll。

编辑: 看起来这并不像看起来那么简单。一些开发人员在此处提到,必须在服务器上安装Office或手动安装更多库。


我在程序集文件夹中找到了Office MSIL。 - Mitesh Jain
如果它很简单,那么在服务器上支持运行Office应用程序...但事实并非如此,所以每个尝试的人都要自己承担风险。 - Alexei Levenkov
@AlexeiLevenkov,有没有更简单的方法? - Mitesh Jain
我怕没有什么比在服务器上安装Office或找到一个可以实现您所需功能的替代库更容易的事情了。但这两者都相当困难... - Martin Zikmund
我该如何在服务器上安装Office? - Mitesh Jain
你不应该......但步骤很简单——购买许可证,安装,希望它能在你的情况下工作。显然,不能保证它会在你的Web服务器帐户下完全工作或不需要努力才能得到至少一些结果......但既然你的工作是免费的,我认为你花很多时间在上面也没有问题。 - Alexei Levenkov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接