【问题标题】:Printing hidden window in WPF在 WPF 中打印隐藏窗口
【发布时间】:2010-12-15 16:50:51
【问题描述】:

我想创建一个 Window 对象,设置一些值,然后直接发送到打印机而不显示它。我认为这是正确的做法,但显示的是空白文档。

PrintDialog dlg = new PrintDialog();

ReportWindow rw = new ReportWindow(); //WPF Window object

var sz = new Size(96*8.5, 96*11);     //size of a paper page, 8.5x11

rw.Measure(sz); rw.Arrange(new Rect(sz)); 

//   rw.Show();  //want to keep it hidden

dlg.PrintVisual(rw, "report printout");

rw.Close(); 

为了验证打印代码是否正常,我将它放在表单加载事件中,调用 Show(),它工作正常。

【问题讨论】:

  • 如果不渲染,我怀疑会生成 Visual。
  • 如果不调用 Show() 就无法使其渲染?
  • 只是一个疯狂的想法,如果您将窗口显示在屏幕外的某个位置,而不在任务栏中显示并且没有激活它会怎样?
  • 可能有效;) 我目前正在调用 Show(),让它自己打印,然后自己调用 close。嘘。
  • 如果 Visibility.Collapsed 会发生什么?

标签: c# wpf xaml printing


【解决方案1】:

无需创建隐藏窗口,您可以使用DocumentPage 渲染 WPF 控件以进行打印。要打印 DocumentPages ,您需要扩展 DocumentPaginator 类。

实现一个简单的DocumentPaginator 的代码将打印出UIElements 中的任何List,如下所示。

class DocumentPaginatorImpl : DocumentPaginator
{
    private List<UIElement> Pages { get; set; }

    public DocumentPaginatorImpl(List<UIElement> pages)
    {
        Pages = pages;
    }

    public override DocumentPage GetPage(int pageNumber)
    {
        return new DocumentPage(Pages[pageNumber]);
    }

    public override bool IsPageCountValid
    {
        get { return true; }
    }

    public override int PageCount
    {
        get { return Pages.Count; }
    }

    public override System.Windows.Size PageSize
    {
        get
        {
            /* Assume the first page is the size of all the pages, for simplicity. */
            if (Pages.Count > 0)
            {
                UIElement page = Pages[0];

                if (page is Canvas)
                    return new Size(((Canvas)page).Width, ((Canvas)page).Height);
                // else if ...
            }

            return Size.Empty;
        }
        set
        {
            /* Ignore the PageSize suggestion. */
        }
    }

    public override IDocumentPaginatorSource Source
    {
        get { return null; }
    }
}

最后,要进行打印,您只需:

dialog.PrintDocument(new DocumentPaginatorImpl(pages), "Print Job Description");

【讨论】:

    【解决方案2】:

    不打印窗口,而是打印该窗口主网格的内容。

    <Grid x:Name="maingrid">
        <!-- All content here -->
    </Grid>
    

    然后在你的代码中

    MyWindow myWindow = new MyWindow();
    PrintDialog printDialog = new PrintDialog();
    printDialog.PrintVisual(myWindow.maingrid, string.Empty);
    myWindow.Close();
    

    【讨论】:

    • 很确定我也尝试过这个选项,但是谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-11-29
    • 2013-09-05
    • 1970-01-01
    • 2022-10-15
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    相关资源
    最近更新 更多