Printing a hidden window in WPF

I have a Window object that I would like to create, set some values, and then send directly to the printer without showing it. I thought this was suitable material, but it shows an empty document.

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 that the print code is in order, I put it in the "Loaded Event" form, Show () is called, and it works fine.

+4
source share
1 answer

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

Below is the code for implementing a simple DocumentPaginator that will output any List from UIElements .

 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, in order to print, you will need:

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

Source: https://habr.com/ru/post/1332241/


All Articles