I am developing a VSTO in Outlook, which calls upon MSWord to create a word document, save it as a PDF after which the VSTO quits word. I am using VS2017 Professional and Office365 - version 16 of MSWord.
If MSWord is not open - the code below works like a treat. However if MSWord is open, I get a warning that "Word Cannot Save the file because it is already open elsewhere (normal.dotm)". Now I know this has been cavassed many times and I have tried all of the solutions that I can locate on StackExchange and elsewhere. The problem was previous solved by referencing answers in this question, but since a recent update of Office365, the same warning has come back.
Below is a subset of the code I am using - all filenames and so forth are valid.
// start word to create PDF file
Word.Application wordApp = new Word.Application();
Word.Document wrdDoc = new Word.Document();
object saveOption = false;
//Word.WdSaveOptions.wdDoNotSaveChanges;
object oMissing = Type.Missing;
Word.Documents d = wordApp.Documents;
try
{
// set the word app invisible
wordApp.Visible = false;
// open the document with the tmpfilename
wrdDoc = d.Open(FileNameIn, Visible: true);
//set the page size ...
//wrdDoc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4;
}
catch (COMException es)
{
throw (es);
}
try
{
//Save/Export our document to a PDF
wrdDoc.ExportAsFixedFormat(OutputFileName: FileNameOut, ExportFormat: Word.WdExportFormat.wdExportFormatPDF,
OpenAfterExport: false, OptimizeFor: Word.WdExportOptimizeFor.wdExportOptimizeForPrint,
Range: Word.WdExportRange.wdExportAllDocument, From: 0, To: 0, Item: Word.WdExportItem.wdExportDocumentContent,
IncludeDocProps: true, KeepIRM: true, CreateBookmarks: Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks,
DocStructureTags: true, BitmapMissingFonts: true, UseISO19005_1: false);
// trick our Word App into thinking that we have been saved
wordApp.NormalTemplate.Saved = true;
}
catch (COMException es)
{
// there is an actual error reporting mechanism here
throw (es);
}
finally
{
try
{
// make our document think its been saved
wrdDoc.Saved = true;
// close our document
wrdDoc.Close(ref saveOption, ref oMissing, ref oMissing);
// trick our Word App into thinking that we have been saved
wordApp.NormalTemplate.Saved = true;
wordApp.Quit(ref saveOption, ref oMissing, ref oMissing);
// release our document object
Marshal.ReleaseComObject(wrdDoc);
// release our documents object
Marshal.ReleaseComObject(d);
// release our application object
Marshal.ReleaseComObject(wordApp);
}
catch (Exception es)
{
// there is an actual error reporting mechanism here
throw (es);
}
finally
{
//
}
}
I'd be obliged for any and all assistance in resolving this issue. Many thanks in advance DWE