Home > Software engineering >  Error Converting Word Document to PDF in C#
Error Converting Word Document to PDF in C#

Time:11-30

I am trying to covert Microsoft Word and Excel documents to PDF in my application. I know there are tools that will make it easier, but we cannot purchase them so am trying to use Microsoft.Office.Interop. I added through NuGet Microsoft.Office.Interop.Word 15.0.4795.1001 and Microsoft.Office.Interop.Excel 15.0.4795.1001. My code is:

    using Microsoft.Office.Interop.Word;

    [HttpPost("getsupportingfilepdf")]
    [ProducesResponseType(typeof(SupportFileResponse), StatusCodes.Status200OK)]
    public ActionResult GetSupportingFilePDF()
    {
            Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
            if (appWord.Documents != null)
            {
                //yourDoc is your word document
                Microsoft.Office.Interop.Word.Document wordDocument = appWord.Documents.Open(@"C:\workspace\DatabaseSRS.docx");
                string pdfDocName = @"C:\workspace\DatabaseSRS.pdf";
                if (wordDocument != null)
                {
                    wordDocument.ExportAsFixedFormat(pdfDocName, WdExportFormat.wdExportFormatPDF);
                    wordDocument.Close();
                }
                appWord.Quit();
            }

When I try to run it, I get: System.IO.FileNotFoundException: Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. The system cannot find the file specified. File name: 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'

I have tried removing and re adding the NuGet packages, but it is still happening. Any ideas on how to resolve this?

Edit: I have Microsoft Office 365 installed on my machine.

CodePudding user response:

I ran into a similar issue as well. Where I was using the wrong office version and installed the library office version. after installing the correct version which matches the library and MS office it worked for me.

Your machine needs Office installed. Version 15.0.0.0 of the library should correspond to Office 2013 - which needs to be installed on your machine other versions of Office will not work. Try installing the relevant office version and it should work fine.

CodePudding user response:

You need to have Microsoft Word (office) installed.

  •  Tags:  
  • c#
  • Related