如何在后台创建文档并在查看器中打印它?

发布于 2024-11-08 22:41:48 字数 203 浏览 4 评论 0原文

我有一个打印字母的功能。它们以 PDF 格式创建,然后拖入 PDFViewer 并打印。

需要某些功能能够更好地控制打印,因此最好在后台线程中打印字母,以便 UI 保持活动状态。但是,当我尝试将文档发送到 PDFViewer 时,出现“跨线程操作”错误。

我不想为每个 1 页文档创建一个新的 PDFViewer。在背景中创建字母然后将其打印的最佳方法是什么?

I have a function that prints letters. They are created in PDF, then pulled into a PDFViewer and printed.

There is demand for some features with greater control over the printing, so it would be good to do the letters in a background thread so the UI stays active. However when I try to send the document to the PDFViewer, I get a "cross thread operation" error.

I don't want to be creating a new PDFViewer for each 1-page document. What's the best way to create the letters in the background, and then get them printed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寂寞笑我太脆弱 2024-11-15 22:41:48

您需要将打印分派到创建 PDFViewer 的线程。因此,如果您在 UI 线程上创建查看器,则需要在完成创建文档后在 UI 线程中执行打印:

Application.Current.Dispatcher.BeginInvoke(() => PrintStuff())

You need to dispatch the printing to the thread which created the PDFViewer. So if you created the viewer on the UI thread you need to execute the printing in the UI thread once you have finished creating the document:

Application.Current.Dispatcher.BeginInvoke(() => PrintStuff())
猥︴琐丶欲为 2024-11-15 22:41:48

我通常解决这个问题的方法是编写一个解决线程问题的方法。我倾向于编写一种扩展方法:

public static class ControlExtensions
{
    public static void Invoke(this Control control, Action action)            
    {            
        if (control.InvokeRequired)
            control.Invoke(action);
        else
            action();
    }
}

用法如下:

pdfViewer.Invoke(() => pdfViewer.Add(pdfDocument));

大多数 WinForms 应用程序都有“UI 线程”的概念,但没有任何一个线程可以完成所有 UI 操作。重要的是,对控件的某些操作只能在创建它们的线程上完成。鉴于此,最安全的做法是要求控件调用您的操作,以便确保在创建它的线程上完成执行。

The way I usually resolve this is to write a method that messes with the threading issue. I tend to write an extension method:

public static class ControlExtensions
{
    public static void Invoke(this Control control, Action action)            
    {            
        if (control.InvokeRequired)
            control.Invoke(action);
        else
            action();
    }
}

And the usage looks like:

pdfViewer.Invoke(() => pdfViewer.Add(pdfDocument));

Most WinForms application have a notion of a "UI Thread", but there isn't any one single thread that all UI most be done on. What is important is that some operations on controls can only be done on threads that they were created on. Given that, it's safest to ask the control to invoke your action so that it will ensure that the execution is done on the thread it was created on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文