[英]Printing hidden window in WPF
我有一个我想创建的 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();
为了验证打印代码是否正常,我将它放在表单 Loaded 事件中,调用 Show(),它工作正常。
无需创建隐藏的 Window,您可以使用DocumentPage呈现 WPF 控件以进行打印。 要打印DocumentPage
s,您需要扩展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");
打印该窗口的主网格的内容,而不是打印窗口。
<Grid x:Name="maingrid">
<!-- All content here -->
</Grid>
然后在你的代码中
MyWindow myWindow = new MyWindow();
PrintDialog printDialog = new PrintDialog();
printDialog.PrintVisual(myWindow.maingrid, string.Empty);
myWindow.Close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.