通过 Word Interop 打印的文档立即从打印队列中消失

Document printed via Word Interop immediately disappears from print queue

我有一个 C# WinForm 应用程序,它通过在书签处放置文本来打开并填写 MS Word dotx 模板,然后尝试打印它,全部使用 MS Word Interop 15。

一切似乎都很顺利,打印对话框显示并正常完成,打印作业显示在打印队列中(即 "See what's printing" window 来自 "Devices and Printers" on MS Windows 10).但是随后该作业在被假脱机之前立即从队列中消失了! (文档出现非常非常短暂,状态为 "Spooling",并且不打印 - 打印机永远无法打印)

这是我的代码(为简洁起见删除了异常检查):

using Word = Microsoft.Office.Interop.Word;
private void Print_Click(object sender, EventArgs e)
{
    // Open the MS Word application via Office Interop
    Word.Application wordApp = new Word.Application();
    Word.Document wordDoc;
    // Open the template
    wordDoc = wordApp.Documents.Add(Template: ContractTemplatePath, Visible: false);
    // Ensure the opened document is the currently active one
    wordDoc.Activate();

    // Set the text for each bookmark from the corresponding data in the GUI
    SetBookmarkText(wordDoc, "Foo", fooTextBox.Text);
    // ... There's a whole bunch of these ... then:

    // Instantiate and configure the PrintDialog
    var pd = new PrintDialog()
    {
        UseEXDialog = true,
        AllowSomePages = false,
        AllowSelection = false,
        AllowCurrentPage = false,
        AllowPrintToFile = false
    };

    // Check the response from the PrintDialog
    if (pd.ShowDialog(this) == DialogResult.OK)
    {
        // Print the document
        wordApp.ActivePrinter = pd.PrinterSettings.PrinterName;
        wordDoc.PrintOut(Copies: pd.PrinterSettings.Copies);
    }

    // Close the document without saving the changes (once the 
    // document is printed we don't need it anymore). Then close 
    // the MS Word application.
    wordDoc.Close(SaveChanges: false);
    wordApp.Quit(SaveChanges: false);
}

我在这里唯一能想到的是,可能是因为我将文件发送到打印机后立即将其删除,然后作业还没有完全发送,所以它自己删除了或其他东西.如果 这种情况,那么我如何确定我需要将文档保留多长时间以及等待它的最佳方式是什么?

编辑:我又做了一点研究(目前没有时间做更多),这表明我可以使用 PrintEnd 事件,但是在使用 Interop 时,我无法立即看出这是否适用。这是否是一种无需轮询即可实现我想要的方法?

一种解决方案是轮询 Word 应用程序的 BackgroundPrintingStatus 属性。它包含仍在打印队列中等待的文档数。虽然此计数大于 0,但仍有文档等待打印。

您可以通过多种方式实现这一目标。这是一个阻止 UI:

的简单循环
// Send document to printing queue here...

while (wordApp.BackgroundPrintingStatus > 0)
{
    // Thread.Sleep(500);
}

// Printing finished, continue with logic

或者你可能想把它包装在一个任务中,这样你就可以在等待的时候做其他事情:

await Task.Run(async () => { while (wordApp.BackgroundPrintingStatus > 0) 
                                   { await Task.Delay(500); } });