none
COMException 0x80010108 The object invoked has disconnected from its clients. RRS feed

  • Question

  • I have some code I am calling to open a DOCX file and save it as a PDF.

    Works great the first time. Often it'll work great the first 3 or 4 times (I am in a loop calling this). But eventually it hits this error. Always when I'm calling a property or method on the doc variable. But different places. Pretty much every call has thrown the exception in my testing.

    Any ideas?

    		public static void Convert(Application word, ProcessPdf process, string inputFile, string outputFile)
    		{
    
    			WdAlertLevel origDisplayAlerts = WdAlertLevel.wdAlertsMessageBox;
    			bool origDisplayRecentFiles = true;
    			bool origDisplayDocumentInformationPanel = false;
    			MsoFeatureInstall origFeatureInstall = MsoFeatureInstall.msoFeatureInstallNone;
    
    			bool[] origWordOptions = new bool[22];
    			defaultWordOptions.CopyTo(origWordOptions, 0);
    
    			bool okToRestore = false;
    			bool createdWordObject = false;
    			bool createdWord = word == null;
    
    			Options wdOptions = null;
    			Documents documents = null;
    			Template normalTemplate = null;
    			Window docWin = null;
    			View docWinView = null;
    			Document doc = null;
    			Window activeWin = null;
    
    			try
    			{
    				if (word == null)
    				{
    					try
    					{
    						word = (Application)Marshal.GetActiveObject("Word.Application");
    					}
    					catch (Exception)
    					{
    						word = new Application();
    						createdWordObject = true;
    					}
    				}
    
    				try
    				{
    					origDisplayAlerts = word.DisplayAlerts;
    					origDisplayRecentFiles = word.DisplayRecentFiles;
    					origDisplayDocumentInformationPanel = word.DisplayDocumentInformationPanel;
    					origFeatureInstall = word.FeatureInstall;
    
    					wdOptions = word.Options;
    					origWordOptions[1] = wdOptions.AllowReadingMode;
    					origWordOptions[2] = wdOptions.PrecisePositioning;
    					origWordOptions[3] = wdOptions.UpdateFieldsAtPrint;
    					origWordOptions[4] = wdOptions.UpdateLinksAtPrint;
    					origWordOptions[5] = wdOptions.WarnBeforeSavingPrintingSendingMarkup;
    					origWordOptions[6] = wdOptions.BackgroundSave;
    					origWordOptions[7] = wdOptions.SavePropertiesPrompt;
    					origWordOptions[8] = wdOptions.DoNotPromptForConvert;
    					origWordOptions[8] = wdOptions.PromptUpdateStyle;
    					origWordOptions[9] = wdOptions.ConfirmConversions;
    					origWordOptions[10] = wdOptions.CheckGrammarAsYouType;
    					origWordOptions[11] = wdOptions.CheckGrammarWithSpelling;
    					origWordOptions[12] = wdOptions.CheckSpellingAsYouType;
    					origWordOptions[13] = wdOptions.DisplaySmartTagButtons;
    					origWordOptions[14] = wdOptions.EnableLivePreview;
    					origWordOptions[15] = wdOptions.ShowReadabilityStatistics;
    					origWordOptions[16] = wdOptions.SuggestSpellingCorrections;
    					origWordOptions[17] = wdOptions.AllowDragAndDrop;
    					origWordOptions[18] = wdOptions.EnableMisusedWordsDictionary;
    					origWordOptions[19] = wdOptions.ShowFormatError;
    					origWordOptions[20] = wdOptions.StoreRSIDOnSave;
    					origWordOptions[21] = wdOptions.SaveNormalPrompt;
    
    					okToRestore = true;
    
    					word.DisplayAlerts = WdAlertLevel.wdAlertsNone;
    					word.DisplayRecentFiles = false;
    					word.DisplayDocumentInformationPanel = false;
    					word.FeatureInstall = MsoFeatureInstall.msoFeatureInstallNone;
    
    					SetWordOptions(wdOptions, silentWordOptions);
    				}
    				catch (SystemException)
    				{
    					// continue on
    				}
    
    				documents = word.Documents;
    				normalTemplate = word.NormalTemplate;
    
    				// Open the source document
    				Object filename = inputFile;
    				Boolean readOnly = false;
    				Boolean visible = createdWordObject;
    				Boolean openAndRepair = true;
    				object oMissing = System.Reflection.Missing.Value;
    
    				doc = documents.OpenNoRepairDialog(ref filename, ref oMissing,
    															 readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    															 ref oMissing, ref oMissing, ref oMissing, ref oMissing, visible,
    															 openAndRepair, ref oMissing, ref oMissing, ref oMissing);
    				doc.Activate();
    
    				// Sometimes the print view will not be available (e.g. for a blog post)
    				// Try and switch view
    				try
    				{
    					// Prevent "property not available" errors, see http://blogs.msmvps.com/wordmeister/2013/02/22/word2013bug-not-available-for-reading/
    					docWin = doc.ActiveWindow;
    					docWinView = docWin.View;
    					float wordVersion = (float) System.Convert.ToDecimal(word.Version, new CultureInfo("en-US"));
    					if (wordVersion >= 15)
    						docWinView.ReadingLayout = false;
    					docWinView.Type = WdViewType.wdPrintPreview;
    					// Hide comments
    					docWinView.RevisionsView = WdRevisionsView.wdRevisionsViewFinal;
    					if (!word.PrintPreview)
    						docWinView.ShowRevisionsAndComments = false;
    				}
    				catch (Exception)
    				{
    					TRAP.trap();
    				}
    
    				// Try to avoid Word thinking any changes are happening to the document
    				// bugbug - do we need to restore these settings?
    				doc.SpellingChecked = true;
    				doc.GrammarChecked = true;
    
    				// Changing these properties may be disallowed if the document is protected
    				if (doc.ProtectionType == WdProtectionType.wdNoProtection)
    				{
    					doc.TrackMoves = false;
    					doc.TrackRevisions = false;
    					doc.TrackFormatting = false;
    				}
    				normalTemplate.Saved = true;
    
    				// Hide the document window
    				if (!createdWordObject)
    				{
    					activeWin = word.ActiveWindow;
    					activeWin.Visible = false;
    					activeWin.WindowState = WdWindowState.wdWindowStateMinimize;
    				}
    
    				// update fields
    				updateDocumentFields(doc, word, inputFile);
    
    				normalTemplate.Saved = true;
    				doc.Saved = true;
    
    				WdExportOptimizeFor quality = WdExportOptimizeFor.wdExportOptimizeForPrint;
    				WdExportItem showMarkup = WdExportItem.wdExportDocumentContent;
    				Boolean includeProps = true;
    				WdExportCreateBookmarks bookmarks = WdExportCreateBookmarks.wdExportCreateHeadingBookmarks;
    				Boolean includeTags = false;
    				Boolean bitmapMissingFonts = true;
    				bool pdfa = process.isPdfA();
    				doc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF, false,
    										 quality, WdExportRange.wdExportAllDocument,
    										 1, 1, showMarkup, includeProps, true, bookmarks, includeTags, bitmapMissingFonts, pdfa);
    
    				doc.Saved = true;
    				normalTemplate.Saved = true;
    				object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
    				doc.Close(ref saveChanges, ref oMissing, ref oMissing);
    			}
    			finally
    			{
    				try
    				{
    					if (okToRestore)
    					{
    						word.DisplayAlerts = origDisplayAlerts;
    						word.DisplayRecentFiles = origDisplayRecentFiles;
    						word.DisplayDocumentInformationPanel = origDisplayDocumentInformationPanel;
    						word.FeatureInstall = origFeatureInstall;
    						SetWordOptions(wdOptions, origWordOptions);
    					}
    				}
    				catch (Exception)
    				{
    					// nada
    				}
    
    				GC.Collect();
    				GC.WaitForPendingFinalizers();
    
    				if (docWinView != null)
    					Marshal.ReleaseComObject(docWinView);
    				if (docWin != null)
    					Marshal.ReleaseComObject(docWin);
    				if (docWin != null)
    					Marshal.ReleaseComObject(docWin);
    				if (doc != null)
    					Marshal.ReleaseComObject(doc);
    				if (activeWin != null)
    					Marshal.ReleaseComObject(activeWin);
    				if (documents != null)
    					Marshal.ReleaseComObject(documents);
    				if (normalTemplate != null)
    					Marshal.ReleaseComObject(normalTemplate);
    				if (wdOptions != null)
    					Marshal.ReleaseComObject(wdOptions);
    
    				if (createdWord)
    				{
    					if (word != null && createdWordObject)
    					{
    						object oMissing = System.Reflection.Missing.Value;
    						word.Quit(ref oMissing, ref oMissing, ref oMissing);
    						// Word needs to be gone before we call this method again - which could be immediately if batch mode
    						Thread.Sleep(1000);
    					}
    
    					if (word != null)
    						Marshal.ReleaseComObject(word);
    				}
    
    				// let everything settle down
    				Thread.Sleep(0);
    				GC.Collect();
    				GC.WaitForPendingFinalizers();
    				Thread.Sleep(0);
    			}
    		}


    What we did for the last 6 months - Made the world's coolest reporting & docgen system even more amazing

    Friday, March 22, 2019 11:37 PM