Brady Moritz
Brady Moritz

Reputation: 8903

Printing hidden window in WPF

I have a Window object I'd like to create, set some values on, and then send straight to the printer without showing it. I thought this was the right stuff to do it, but shows a blank doc.

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

To verify the printing code is ok, i put it inside the form Loaded event, call Show(), and it works fine.

Upvotes: 5

Views: 2834

Answers (2)

J-W
J-W

Reputation: 1

Instead of printing the window, print the content of the main grid of that window.

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

Then in your code

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

Upvotes: -1

utopianheaven
utopianheaven

Reputation: 1277

There is no need to create a hidden Window, you can render WPF controls for printing by using a DocumentPage. To print DocumentPages , you will need to need to extend the DocumentPaginator class.

The code to implement an a simple DocumentPaginator that will print out any List of UIElements is below.

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

Finally, to do the printing, you would only need to:

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

Upvotes: 3

Related Questions