我正在使用 word 自动化生成一个 docx 文件,然后将其打印出来。这是我的基本代码。我发现在adoc.PrintOut之后我必须等待一段时间,否则打印可能会失败。似乎是因为我在那之后关闭了文件。在文件关闭之前,word 还没来得及打印出来。所以,基本上, adoc.PrintOut 是非阻塞的(这可能不是正确的术语)。现在,我等待 10 秒钟,它工作正常。但是,它对此有更优雅的解决方案吗?我的意思是,如何等到 PrintOut 完成,然后关闭文档?
谢谢
object yes = true;
object no = false;
object missing = System.Reflection.Missing.Value;
Word.Application wordApp = new Word.Application();
object fileName = originalFileName;
Word.Document adoc = null;
try
{
adoc = wordApp.Documents.Open(ref fileName,
ref missing, ref no, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref yes, ref missing, ref missing, ref missing, ref missing);
adoc.Activate();
/*
some other processing
*/
object sFile = fileName;
adoc.PrintOut(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
// http://msdn.microsoft.com/en-us/library/b9f0ke7y
//adoc.PrintPreview();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(TimeSpan.FromSeconds(1));
Application.DoEvents();
}
//adoc.Save();
object savechanges = Word.WdSaveOptions.wdDoNotSaveChanges; //.wdSaveChanges;
object originalFormat = Word.WdOriginalFormat.wdWordDocument;
object routeDocument = missing; // Type.Missing; // true;
((Word._Document)adoc).Close(ref savechanges, ref originalFormat, ref routeDocument);
((Word._Application)wordApp).Quit(ref savechanges, ref missing, ref missing);
adoc = null;
wordApp = null;
}
catch
{
}
finally
{
/*
some dispose work
*/
// do it twice to release all memory
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}