I wrote a small code to convert a word-document to pdf.
public static class WordToPDF
{
public static bool ExportDocumentToPDF(string DocumentFilename, string PDFFilename)
{
bool StillRunning = false;
if (!System.IO.File.Exists(DocumentFilename)) { throw new System.Exception("ERROR: File " + DocumentFilename + " not found for opening!"); }
Microsoft.Office.Interop.Word.Application WDApp = WordToPDF.GetWordApplication(out StillRunning);
Microsoft.Office.Interop.Word.Document Docu = WordToPDF.GetDocument(DocumentFilename, ref WDApp);
WordToPDF.Word2PDF(ref Docu, PDFFilename);
Docu.Close();
Docu = null;
if (!StillRunning) {
WDApp.Quit(false);
//if(WDApp != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(WDApp); }
WDApp = null;
//KillWord();
}
return StillRunning;
}
private static void KillWord()
{
foreach(System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD")) { p.Kill(); }
}
private static Microsoft.Office.Interop.Word.Application GetWordApplication(out bool StillRunning)
{
Microsoft.Office.Interop.Word.Application WDApp = null;
if (System.Diagnostics.Process.GetProcessesByName("WINWORD").Count() > 0)
{
StillRunning = true;
return System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") as Microsoft.Office.Interop.Word.Application;
}
else
{
StillRunning = false;
WDApp = new Microsoft.Office.Interop.Word.Application();
return WDApp;
}
}
private static Microsoft.Office.Interop.Word.Document GetDocument(string Filename, ref Microsoft.Office.Interop.Word.Application WDApp)
{
if (WDApp == null) { throw new System.Exception("ERROR: Microsoft.Office.Interop.Word.Application is not referenced!"); }
if (!System.IO.File.Exists(Filename)) { throw new System.Exception("ERROR: File " + Filename + " not found for opening!"); }
try
{
Microsoft.Office.Interop.Word.Document Doc = WDApp.Documents.Open(Filename);
return Doc;
}
catch (System.Exception ex) { throw new System.Exception("ERROR: Unable to open Word document " + Filename + System.Environment.NewLine + "Detailed error message: " + ex.Message); }
}
private static void Word2PDF(ref Microsoft.Office.Interop.Word.Document Docu, string OutputFilename)
{
try
{
Docu.ExportAsFixedFormat(OutputFilename, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
}
catch (System.Exception ex) { throw new System.Exception("ERROR: Unable to export Document to PDF file." + System.Environment.NewLine + "Detailed information: " + ex.Message); }
}
}
The conversation works finde, but after the code is finished, in my task manager there is still an process called WINWORD.EXE *32
which was not there before.
I don't understand that, because in line 13, I quite the Word.Application object. Does anybody know help?
Thanks and regard, Jan