locked
Convert word to pdf file in asp.net in c# RRS feed

  • Question

  • Hello,

    I want to convert word file for pdf file.So Im using 2007 Microsoft Office Add-in: Microsoft Save as PDF.I download this add in and write code.It is work on my local computer.But it is not work on my server.I take an this error message:

    Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154. 

    How can I work this application? or How can ı create a pdf in my asp.net webpage ?Can you help me please?

     

    I write This code:

     

    using System;
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    using Microsoft.Office.Interop.Word;
    
    public class Word2Pdf
    {
     Microsoft.Office.Interop.Word.Application _Word = new Microsoft.Office.Interop.Word.Application();
     object _MissingValue = System.Reflection.Missing.Value;
    
     public void Convert(string wordFileName, out string pdfFileName)
     {
      _Word.Visible = false;
      _Word.ScreenUpdating = false;
    
      // Cast as Object for word Open method
      object filename = (object)wordFileName;
    
      // Use the dummy value as a placeholder for optional arguments
      Document doc = _Word.Documents.Open(ref filename, ref _MissingValue,
       ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue,
       ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue,
       ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue);
      doc.Activate();
    
      object outputFileName = pdfFileName = Path.ChangeExtension(wordFileName, "pdf");
      object fileFormat = WdSaveFormat.wdFormatPDF;
    
      // Save document into PDF Format
      doc.SaveAs(ref outputFileName,
       ref fileFormat, ref _MissingValue, ref _MissingValue,
       ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue,
       ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue,
       ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue);
    
      // Close the Word document, but leave the Word application open.
      // doc has to be cast to type _Document so that it will find the
      // correct Close method.    
      object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
      ((_Document)doc).Close(ref saveChanges, ref _MissingValue, ref _MissingValue);
      doc = null;
    
      // word has to be cast to type _Application so that it will find
      // the correct Quit method.
      ((_Application)_Word).Quit(ref _MissingValue, ref _MissingValue, ref _MissingValue);
      _Word = null;
     }
    }
    

    Best Regards

    Tuesday, May 31, 2011 11:18 AM

Answers

  • uygurkubra,

    The problem doesn't lie in your code.  As I said, Microsoft chagned the way services run between 2003 and 2008.  Odds are your code will work correctly on a Server 2003 machine, but there isn't going to be a whole lot you can do to get it to run on Server 2008.  The problem occurs because there is no desktop session for services anymore.  I've seen work-arounds that involve creating one at runtime, but that's not anywhere you want to go for a production quality operation.

    Microsoft's offered 'solution' to server side rendering is to use the Word services that come with sharepoint, but these methods require your document to be housed inside of a sharepoint repository and for your conversion job to run in a sharepoint context ... To me this is akin to using a sledgehammer to push in a thumb tack.

    (very) Short Term: If you can get away with it, I'd suggest downgrading your server OS to Server 2003.  Long Term you'll want to look for third party converson components--there area a few out there.  Or work towards implementing Microsoft's sharepoint method.

    Cheers


    This signature unintentionally left blank.
    • Proposed as answer by Nick F. _ Tuesday, June 7, 2011 7:29 PM
    • Marked as answer by Paul Zhou Monday, July 11, 2011 9:25 AM
    Tuesday, June 7, 2011 1:13 PM

All replies

  • To make that work you would need to install word on the server machine. 

    However note that if the server is running Windows Server 2008, it will not work anyway.  Changes to the service model between Server 2003 and Server 2008 cause Word (and probably the other office applications) to fail.

    Lastly, You're passing defaults for many paramters to Open that you might consider using real values to reduce the possibility that word will open a dialog box.    Consider:

    /// <summary>
    /// Opens a word document
    /// </summary>
    /// <param name="fileName"></param>
    public void Open(string fileName)
    {
      object oFileName = fileName;
    
      if (string.IsNullOrEmpty(fileName))
        throw new ArgumentException("Argument is required.", "fileName");
    
      /*
       * close up any document that might already be open
       */
      Close();
    
      ts.TraceEvent(TraceEventType.Verbose, 0, "word.Documents.Open(\"{0}\");", fileName);
      try
      {
        document = word.Documents.Open(ref oFileName, // FileName
                        ref oFalse,  // ConfirmConversions (false=no dialog)
                        ref oFalse,  // ReadOnly
                        ref oFalse,  // AddToRecentFiles
                        ref oMissing, // PasswordDocument
                        ref oMissing, // PasswordTemplate
                        ref oMissing, // Revert
                        ref oMissing, // WritePasswordDocument
                        ref oMissing, // WritePasswordTemplate
                        ref oMissing, // Format
                        ref oMissing, // Encoding
          /*
          ** passing oFalse for Visible here causes an exception 
          ** when the document is printed. Rely on oMissing to 
          ** grab the correct value from the application state.
          */
                        ref oMissing, // Visible
                        ref oFalse,  // OpenAndRepair (false=no dialog)
                        ref oMissing, // DocumentDirection
                        ref oTrue,   // NoEncodingDialog
                        ref oMissing); // XMLTransform
      }
      catch (COMException x)
      {
        /*
         * If the document contains macros that cannot be located, an
         * exception 0x800A175D will be raised by call to Open.
         */
        if ((uint)x.ErrorCode == 0x800A175D && 1 == word.Documents.Count)
          x.Data.Add("Detail", "Failed to open word document due to macros.");
    
        throw;
      }
    
      /*
       * Server 2008 "opens" the document but returns null...
       * call that broken
       */
      if (null == document)
        throw new Exception("No document after successful open.");
    }
    
    
    

     


    This signature unintentionally left blank.
    Tuesday, May 31, 2011 12:07 PM
  • Is this Some kind of User Interactive application or a kind of widow service that run on server.

    If it is non user interactive application than this will hard to make it work:

    http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/bb711a49-e66c-47e6-a169-48bcbdf402d7

    http://support.microsoft.com/?id=257757 


    -------------------------------------

    Best Regards

    Sanjay Pant

    Sr. Software Engg. Metadesign Solutions

    Wednesday, June 1, 2011 7:14 AM
  • Hello,

    Thank you all post.I tried your suggest.I have windows server 2008 X64 bit.I installed office  but it doesnt work.Ican take same an errror.What else ? How can I convert to word file as pdf file in asp.net codebehind or convert to pdf my asp.net web page

    Thank you for your interest.

     

    Best Regards

    Monday, June 6, 2011 1:05 PM
  • Hi,

    If the suggestions don't make sense, please post thread in  Word for Developers forum to get better support.

    Thank you for your posting and understanding.


    Paul Zhou [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, June 7, 2011 7:58 AM
  • uygurkubra,

    The problem doesn't lie in your code.  As I said, Microsoft chagned the way services run between 2003 and 2008.  Odds are your code will work correctly on a Server 2003 machine, but there isn't going to be a whole lot you can do to get it to run on Server 2008.  The problem occurs because there is no desktop session for services anymore.  I've seen work-arounds that involve creating one at runtime, but that's not anywhere you want to go for a production quality operation.

    Microsoft's offered 'solution' to server side rendering is to use the Word services that come with sharepoint, but these methods require your document to be housed inside of a sharepoint repository and for your conversion job to run in a sharepoint context ... To me this is akin to using a sledgehammer to push in a thumb tack.

    (very) Short Term: If you can get away with it, I'd suggest downgrading your server OS to Server 2003.  Long Term you'll want to look for third party converson components--there area a few out there.  Or work towards implementing Microsoft's sharepoint method.

    Cheers


    This signature unintentionally left blank.
    • Proposed as answer by Nick F. _ Tuesday, June 7, 2011 7:29 PM
    • Marked as answer by Paul Zhou Monday, July 11, 2011 9:25 AM
    Tuesday, June 7, 2011 1:13 PM
  • I think you can not use COM classes with the ASP.NET or any web application. You can just use in Windows Application because of the security measures.
    Computer Engineer
    Wednesday, July 6, 2011 7:17 AM
  • Hello,

     for Converting word to pdf file in asp.net in c#, Spire.Doc can do it well.

    using System;
    using Spire.Doc;
    using Spire.Doc.Documents;
    namespace WordToPDF
    {
      class Program
      {
        static void Main(string[] args)
        {
          //Create a new document
          Document document = new Document();
          //Load word 2007 file from disk.
          document.LoadFromFile("WordFile.docx");
          //Save doc file to pdf.
          document.SaveToFile("Sample.pdf", FileFormat.PDF);
        }
      }
    }

     
     Hope help to every one.

    Thursday, September 22, 2011 2:29 AM
  • Hello Lvess,

    Thanks for your answer.I know spire.doc but is not free component and I dont test this component.I must take a license.Thanks your answer

    Thursday, September 22, 2011 1:51 PM
  • Hello :)

    I think you may to use "PDF Metamorphosis" .Net. Supports ASP .Net and C#. Don't require nothing special, only .Net 1.1 platform or higher.

    SAmple code for the converting Word (RTF) file to PDF in ASP.Net/C#:

            SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
            string wordFileName = "...";
            
            byte[] pdf = p.RtfToPdfConvertFileToByte(wordFileName);
    
            //show PDF
            if (pdf != null)
            {
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = "application/PDF";
                Response.BinaryWrite(pdfBytes);
                Response.Flush();
                Response.End();
            }
    

    Friday, March 9, 2012 7:42 AM
  • HI Lvess,

    This method is really simple, but I still have two questions:

    1. I have an image in my word document and I want to convert my doc file to PDF, is the image still there after conversion?

    2. Can Spire.Doc convert html to doc, I want to convert html to word also?

    Please reply me!Thanks!

    Tuesday, July 10, 2012 7:39 AM
  • Hi,

    Here is one more simple solution on how to convert Word to PDF in C#:

    // Convert Word file (DOCX) to PDF.
    DocumentModel.Load("Doc.docx", LoadOptions.DocxDefault).Save("Doc.pdf");

    Friday, July 20, 2012 7:46 AM
  • Hi, Michelle

    I just wanted to add that I used Jeniffers solution and found out that it also can convert HTML to Word in C# in the same manner:

    DocumentModel.Load("Sample.html").Save("Sample.docx");

    Regards

    Wednesday, July 10, 2013 7:01 AM
  • Using "Spire.doc for NET" can help you to avoid the error which is occured in your operation.I provide the codes ,hope can help you /download address:http://www.nuget.org/packages/Spire.Doc/

    1. Declare a document and load document which you prepare by using ocument.LoadFromFile() method. The parameter passed to this method is file name string.
    2. Save Word document as PDF by using document.SaveToFile() method. Parameters passed to this method is file name string and file format. The file format must be PDF.

     

    [C#]
    using System;
    using Spire.Doc;
    using Spire.Doc.Documents;
    
    namespace DoctoPDF
    {
        class toPDF
        {
            static void Main(string[] args)
            {
                //Load Document
                Document document = new Document();
                document.LoadFromFile(@"E:\work\documents\TestSample.docx");
    
                //Convert Word to PDF
                document.SaveToFile("toPDF.PDF", FileFormat.PDF);
    
                //Launch Document
                System.Diagnostics.Process.Start("toPDF.PDF");
            }
        }
    }
    

     

    [Visual Basic]
    Imports System
    Imports Spire.Doc
    Imports Spire.Doc.Documents
    
    Namespace DoctoPDF
        Friend Class toPDF
            Shared Sub Main(ByVal args() As String)
                'Load Document
                Dim document As New Document()
                document.LoadFromFile("E:\work\documents\TestSample.docx")
    
                'Convert Word to PDF
                document.SaveToFile("toPDF.PDF", FileFormat.PDF)
    
                'Launch Document
                System.Diagnostics.Process.Start("toPDF.PDF")
            End Sub
        End Class
    End Namespace
    


    Tuesday, August 27, 2013 3:55 AM