首页 文章

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

提问于
浏览
0

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

一切似乎都很顺利,打印对话框显示并完成确定,打印作业显示在打印队列中(即MS Windows 10上“设备和打印机”中的“查看打印”窗口) . 但是,在可以假脱机之前,作业会立即从队列中消失! (文件在“假脱机”状态下非常简短地显示,并且不打印 - 打印机永远不会得到工作)

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

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);
}

我在这里唯一可以想到的可能是因为我在完全发送后立即取消了该文档,因此它会将其自身或其他东西移除 . 如果是这种情况,那么我如何确定需要多长时间保留文档以及等待它的最佳方式是什么?

EDIT: 我已经完成了另一小部分研究(目前没有时间对此进行更多研究)这表明我可以使用PrintEnd事件,但我无法立即看到这在使用Interop时是否适用 . 它是一种在没有民意调查的情况下实现我想要的方法吗?

1 回答

  • 1

    一种解决方案是轮询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); } });
    

相关问题