WPF Printing – some issues resolved

After my recent post I emailed the development team at Microsoft and some issues have been worked out.

When printing a landscape document via the preview control you need to set a print ticket on the FixedDocument before displaying it in preview.

FixedDocument x = new FixedDocument();
PrintTicket pt = new PrintTicket();
pt.PageOrientation = PageOrientation.Landscape;
x.PrintTicket = pt;

You can then set the Document property of the DocumentViewer and when you print from there it should print landscape.

I haven’t tested this in anger because I moved on and found a neater approach (and I didn’t really want a preview of what I was printing I simply wanted to avoid wasting paper and ink).

I’ve since set up a PDF print queue using RedMon (great wee utility) and GhostScript so I’ve been using that to produce PDFs which I can look at.

A much tidier approach to printing involves printing objects that derive from the Visual class (and all FrameworkElement objects in  WPF do). So I created a new Page (although you could also base a new class on UserControl) and called it EntrySheet, set up the content as I wish and then to print I do the following:

PrintDialog pd = new PrintDialog();
pd.PrintTicket.PageOrientation = PageOrientation.Landscape;

Size ps = new Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight);

EntrySheet p = new EntrySheet();
p.Width = ps.Width;
p.Height = ps.Height;

p.Measure(ps);
p.Arrange(new Rect(new Point(0, 0), ps));
p.UpdateLayout();

pd.PrintVisual(p, "Entry Sheet");

Because the EntrySheet object is not being displayed prior to printing, you must call Measure and Arrange so that it’s content can be dimensioned and layed out. UpdateLayout isn’t always needed but I found that if your Visual includes a DataGrid then this step is essential.

The issue I haven’t been able to resolve is a DataGrid where the columns have been given star dimensions.

Tags: ,

Leave a Reply

 
Trojan Archer