Search code examples
c#wpfprintingxpsprintdialog

Ignored Paper Size in PrintDialog/XPS Document Writer


I am trying to print with WPF's PrintDialog class (namespace System.Windows.Controls in PresentationFramework.dll, v4.0.30319). This is the code that I use:

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

The problem is no matter what Paper Size I select for "Microsoft XPS Document Writer", the generated XPS, always, has the width and height of "Letter" paper type:

This is the XAML code I can find inside XPS package:

<FixedPage ... Width="816" Height="1056">


Solution

  • Changing the paper size in the print dialog only affects the PrintTicket, not the FixedPage content. The PrintVisual method produces Letter size pages, so in order to have a different page size you need to use the PrintDocument method, like so:

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