This is part 2 of a series about printing in WPF, in the previous part we printed the content of a WPF visual, in this part we’ll create and print a fixed document, in the end of the previous post I wrote well deal with choosing printers and setting up print settings – but actually printing is more interested and I’ll get to printer management later in this series.
Printing a FixedDocument is the simplest way to do some “real” printing with control over paging, margin and everything else.
The code is much longer than the examples in the previous post but it’s not complicated, take the program from the previous post and replace the content of Print_Click with the following code.
First we have to get the printer settings, we especially need the page size in order to create a document with the same page size, we’ll just use PrintDialog like we did before:
// select printer and get printer settings
PrintDialog pd = new PrintDialog();
if (pd.ShowDialog() != true) return;
Now create a document and set it’s page size:
// create a document
FixedDocument document = new FixedDocument();
document.DocumentPaginator.PageSize = new Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight);
Create a page and again set the page size:
// create a page
FixedPage page1 = new FixedPage();
page1.Width = document.DocumentPaginator.PageSize.Width;
page1.Height = document.DocumentPaginator.PageSize.Height;
Create a TextBlock and add it to the page:
// add some text to the page
TextBlock page1Text = new TextBlock();
page1Text.Text = "This is the first page";
page1Text.FontSize = 40; // 30pt text
page1Text.Margin = new Thickness(96); // 1 inch margin
And add the page to the document, this is a little tricky because we need to use a PageContent object as an intermediary and it looks like there is no way to add the page to the page content, the trick is to use the IAddChild interface – according to the documentation you’re not supposed to use IAddChild directly but it’s the only way to build a fixed document.
// add the page to the document
PageContent page1Content = new PageContent();
Now repeat all the steps for the second page:
// do the same for the second page
FixedPage page2 = new FixedPage();
page2.Width = document.DocumentPaginator.PageSize.Width;
page2.Height = document.DocumentPaginator.PageSize.Height;
TextBlock page2Text = new TextBlock();
page2Text.Text = "This is NOT the first page";
page2Text.FontSize = 40;
page2Text.Margin = new Thickness(96);
PageContent page2Content = new PageContent();
And print the resulting document:
// and print
pd.PrintDocument(document.DocumentPaginator, "My first document");
The result of all this work is this very impressive document:
At point we are wasting a lot of paper and a print preview feature starts to look real nice, on the next post we’ll talk briefly about all the “magic numbers” in this sample code and in the post after that we’ll jump right into building a print preview window.
posted @ Monday, April 20, 2009 12:56 PM