我试图打印WPF的PrintDialog
类(命名空间System.Windows.Controls in PresentationFramework.dll, v4.0.30319)。这是我使用的代码:
private void PrintMe()
{
var dlg = new PrintDialog();
if (dlg.ShowDialog() == true)
{
dlg.PrintVisual(new System.Windows.Shapes.Rectangle
{
Width = 100,
Height = 100,
Fill = System.Windows.Media.Brushes.Red
}, "test");
}
}
问题是无论我为"Microsoft XPS Document Writer"选择什么尺寸的纸张,生成的XPS,总是具有"字母"纸张类型的宽度和高度:
这是我可以在XPS包中找到的XAML代码:
<FixedPage ... Width="816" Height="1056">
在打印对话框中更改纸张大小只影响PrintTicket,而不影响FixedPage内容。PrintVisual方法生成字母大小的页面,因此为了拥有不同的页面大小,您需要使用PrintDocument方法,如下所示:
private void PrintMe()
{
var dlg = new PrintDialog();
FixedPage fp = new FixedPage();
fp.Height = 100;
fp.Width = 100;
fp.Children.Add(new System.Windows.Shapes.Rectangle
{
Width = 100,
Height = 100,
Fill = System.Windows.Media.Brushes.Red
});
PageContent pc = new PageContent();
pc.Child = fp;
FixedDocument fd = new FixedDocument();
fd.Pages.Add(pc);
DocumentReference dr = new DocumentReference();
dr.SetDocument(fd);
FixedDocumentSequence fds = new FixedDocumentSequence();
fds.References.Add(dr);
if (dlg.ShowDialog() == true)
{
dlg.PrintDocument(fds.DocumentPaginator, "test");
}
}