title: Convert Word to PDF in background process either via c# or IronPython
body: <p>I have found many examples online about converting word (.docx) file to .pdf file.</p>
  
  <p>It works fine when I run from UI thread.
  But the moment I execute it on background process. then it fails.
  Is there some way to convert Word to PDF via background process execution ?</p>
  
  <p>Below are the IronPython and c# code that works on UI thread.</p>
  
  <p><strong>IronPython:</strong></p>
  
  <pre class="lang-python prettyprint-override"><code>import sys
  import clr
  import System
  from System.Text import StringBuilder
  from System.IO import DirectoryInfo, File, FileInfo, Path, StreamWriter
  
  clr.AddReference("Microsoft.Office.Interop.Word")
  import Microsoft.Office.Interop.Word as Word
  
  def ConvertWordToPDF(wordDocFullPath):
      """
      &lt;Script&gt;
      &lt;Author&gt;SNI&lt;/Author&gt;
      &lt;Description&gt;Converts Word document to PDF.&lt;/Description&gt;
      &lt;Parameters&gt;
      &lt;Parameter name="wordDocFullPath" type="string"&gt;Word document full path.&lt;/Parameter&gt;
      &lt;/Parameters&gt;
      &lt;ReturnValue type="string"&gt;PDF full path&lt;/ReturnValue&gt;
      &lt;/Script&gt;
      """   
      wordDocInfo = FileInfo(wordDocFullPath)
      pdfFullPath = Path.Combine(wordDocInfo.DirectoryName, wordDocInfo.Name.TrimEnd(wordDocInfo.Extension.ToCharArray()) + '.pdf')
  
      word_application = Word.ApplicationClass()
      word_application.visible = False
  
      wordDocument = word_application.Documents.Open(wordDocFullPath);
      if wordDocument:
          wordDocument.ExportAsFixedFormat(pdfFullPath, Word.WdExportFormat.wdExportFormatPDF);
          wordDocument.Close()
          word_application.Quit()
          word_application = None
      else:
          print 'failed to initialize word document'
  
      print pdfFullPath
      return pdfFullPath`
  </code></pre>
  
  <p><strong>c# code:</strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>public string Convert(string wordDocPath)
  {
      string pdfPath = string.Empty;
  
      try
      {
          Microsoft.Office.Interop.Word.Application word = null;
          Document doc = null;
  
          // C# doesn't have optional arguments so we'll need a dummy value
          object oMissing = System.Reflection.Missing.Value;
          object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
  
          try
          {
              word = new Microsoft.Office.Interop.Word.Application();
  
              Thread.Sleep(5000);
  
              word.Visible = false;
              word.ScreenUpdating = false;
              doc = word.Documents.Open(wordDocPath);
              pdfPath = wordDocPath.Replace(".docx", ".pdf");
  
              doc.ExportAsFixedFormat(
                          pdfPath,
                          Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF,
                          OptimizeFor: Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen,
                          BitmapMissingFonts: true, DocStructureTags: false);
  
              ((Microsoft.Office.Interop.Word._Document)doc).Close();
              ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
          }
          catch
          {
              if (doc != null)
              {
                  ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
              }
  
              if (word != null)
              {
                  ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
              }
              throw;
          }
      }
      catch (Exception ex)
      {
          var st = new StackTrace(ex, true);
          // Get the top stack frame
          var frame = st.GetFrame(0);
          // Get the line number from the stack frame
          var line = frame.GetFileLineNumber();
  
          throw new Exception("Line Number: " + line.ToString() + "  " + ex.ToString());
      }
      return pdfPath;
  }
  </code></pre>