Implement XPS printing and preview in WPF

Source: Internet
Author: User
Tags temporary file storage

This article is from blog Author: Luo Xiaoping


XPS is. net, which is a fixed layout description format. It is not only the basis for WPF printing and output, but also can be used as an independent file format. Therefore, when designing the printing function of WPF, we had to think of XPS printing first. Since there are not many introductions on XPS printing for WPF design on the Internet, and the xps printing design introduced on msdn is also based on. net hard coding method to complete, the WYSIWYG support is not good. Therefore, I developed my own fixeddocument-based Printing Service Based on the XPS printing API. The built-in documentviewer document display and printing functions are called.

I. First, let's take a look at the printing service for three documents of XPS in WPF:

1. Print fixed document classes, including fixedpage, fixeddocument, and fixeddocumentsequence. These classes are used to submit a single page, a whole document, or a printing containing several files.

2. Print the document class of streaming, mainly the flowdocument class, which provides printing of the Document Stream.

3. Print the visual element class, which is mainly a visual and derived class object and provides printing for the visual tree.

Ii. Next let's take a look at the important classes of the XPS printing service:

1. xpsdocument: a service document class for printing packages, such as loading and saving XPS documents or adding thumbnails.

Public xpsdocument (string path, fileaccess packageaccess)

Initializes a new instance of the xpsdocument class in the specified package file with the default delimiter scan, resource, and compression options.

Public static xpsdocumentwriter createxpsdocumentwriter (xpsdocument)

Create an xpsdocumentwriter for compiling xpsdocument.

Public fixeddocumentsequence getfixeddocumentsequence ()

Returns the fixed document sequence at the package root position.

2. xpsdocumentwriter: The base class of the print operation. It is used to print disk operations and the organizational structure of the Object Tree.

Void write () synchronously writes data to XPS documents or print queues.

Void writeasync () asynchronously writes the xpsdocument or printqueue that has created xpsdocumentwriter.

3. Basic Ideas:

To provide printed documents to users and use the WPF built-in print display framework, we use the WPF documentviewer class to provide document display and printing services. Two main functions are implemented here:

Iv. Specific implementation:

1. Define a help class for file printing:

Public class filehelper {......}

In this class, we implement two methods.

Public static string openxpsfilefromdialog ()


Openfiledialog = new openfiledialog ();

Openfiledialog. Filter = "XPS document files (*. XPS) | *. XPS ";

If (openfiledialog. showdialog () = true)

Return openfiledialog. filename;


Return NULL;


This static method displays the selection dialog box to provide the file storage location.

Public static bool savexps (fixedpage page, bool issaved ){

Fixeddocument fixeddoc = new fixeddocument (); // create a document fixeddoc. documentpaginator. pagesize = new size (96*8.5, 96*11 );

Pagecontent = new pagecontent ();

(Iaddchild) pagecontent). addchild (PAGE );

Fixeddoc. pages. Add (pagecontent); // upload the object to the current document.

String containername = getxpsfromdialog (issaved );

If (containername! = NULL ){

Try {

File. Delete (containername );


Catch (exception e ){

MessageBox. Show (E. Message );


Xpsdocument _ xpsdocument = new xpsdocument (containername, fileaccess. Write );

Xpsdocumentwriter xpsdw = xpsdocument. createxpsdocumentwriter (_ xpsdocument );

Xpsdw. Write (fixeddoc); // write the XPS File

_ Xpsdocument. Close ();

Return true;


Else return false;


This method is mainly used to save the XPS file.

Static xpsdocument xpspackage = NULL;

Public static void loaddocumentviewer (string xpsfilename, documentviewer viewer ){

Xpsdocument oldxpspackage = xpspackage; // Save the original XPS

Xpspackage = new xpsdocument (xpsfilename, fileaccess. Read, compressionoption. notcompressed); // read the document from the file

Fixeddocumentsequence = xpspackage. getfixeddocumentsequence (); // obtain fixeddocumentsequence from the xps Document Object.

Viewer. Document = fixeddocumentsequence as idocumentpaginatorsource;

If (oldxpspackage! = NULL)

Oldxpspackage. Close ();

Xpspackage. Close ();


This method is used to load the documents in the XPS file into the documentviewer display container.

2. In order not to add documents by hard encoding, we have added a fixedpage page. Note that since the fixedpage class is clearly marked as sealed, we cannot addCodeTo hide a file, you can only add elements in XAML and bind data using context datacontext. Here we have added a fixedpage for printview. Of course, data binding is also used here. Related code:


Xmlns = ""

Xmlns: x = ""

Xmlns: I = "" xmlns: Ei = ""

X: Name = "window"

Uselayoutrounding = "true"

Width = "640" Height = "480">

<Grid X: Name = "layoutroot" datacontext = "{binding collection, source = {staticresource simpledatasource}">

<ComboBox X: Name = "datacombo" verticalalignment = "bottom" margin = "-26, 0, 22, -503 "opacity =" 0 "itemssource =" {binding mode = oneway} "/>

<Grid X: Name = "frame" margin = "0, 0, 0">

<Canvas margin = "0, 0, 116,8">

<Rectangle margin = "0" stroke = "black" fill = "# ff4b4b9f" opacity = "0.4" radiusx = "5" radiusy = "5" width = "637" Height = "& quot; 473 & quot; canvas. left = "3" canvas. top = "2"/>

<Grid Height = "422" width = "506" canvas. Left = "70" canvas. Top = "34" datacontext = "{binding selecteditem, elementname = datacombo}">

<Grid. rowdefinitions>

<Rowdefinition Height = "Auto"/>

<Rowdefinition Height = "Auto"/>


</Grid. rowdefinitions>

<Label X: name = "name" content = "{binding name}" fontsize = "48" fontfamily = "script Mt bold" margin = "0" horizontalalignment = "center"/>

<Label X: name = "prefill" content = "{binding photo}" fontsize = "48" fontfamily = "script Mt bold" margin = "0" horizontalalignment = "center" grid. row = "1"/>

<Image X: Name = "photo" margin = "8, 0" grid. Row = "2" Source = "{binding Preprocessor}"/>






3. added a window form with a documentviewer object embedded in it as the printwindow for display of XPS documents.


Xmlns = ""

Xmlns: x = ""

X: class = "workpiece. printwindow"

X: Name = "window"

Title = "printwindow"

Uselayoutrounding = "true"

Width = "640" Height = "480" loaded = "window_loaded">

<Grid X: Name = "layoutroot">

<Documentviewer X: Name = "docviewer"/>



At the same time, the loaded event is reloaded in the Post-code file to load the document

// Pass a public data class
Public String fixeddocfile;
Private void window_loaded (Object sender, routedeventargs E)
Filehelper. loaddocumentviewer (fixeddocfile, docviewer );

4. In order to pass data to the document, an example data source is added to expression blend.

5. On the home page, we have implemented the dynamic loading and printing of pages, which is implemented through the loadcomponent () method of the application class, previously, I used the load method of the xamlreader class to load the file. However, to use this method, you must set *. set the XAML file to building action and set it to content. Otherwise, the data file cannot be found during Publishing. The method is as follows:

Private void resutlbtn_click (Object sender, system. Windows. routedeventargs E)


// Todo: Add event handler implementation here.

Uri printviewuri = new uri ("/workpiece; component/printview. XAML", urikind. Relative );

Fixedpage printpage = (fixedpage) application. loadcomponent (printviewuri );

ComboBox combo = printpage. findname ("datacombo") as ComboBox;

Combo. selectedindex = namecombo. selectedindex; // Data Synchronization

Filehelper. savexps (printpage, false );

String xpsfilename = filehelper. getxpsfromdialog (false); // get temporary file storage

Printwindow window = new printwindow ();

Window. fixeddocfile = xpsfilename;

Window. Show ();


6. How to store XPS files

// Save the file

Private void otherbtn_click (Object sender, system. Windows. routedeventargs E)


Uri printviewuri = new uri ("/workpiece; component/printview. XAML", urikind. Relative );

Fixedpage printpage = (fixedpage) application. loadcomponent (printviewuri );
ComboBox combo = printpage. findname ("datacombo") as ComboBox;

Combo. selectedindex = namecombo. selectedindex; // data synchronization if (filehelper. savexps (printpage, true ))

MessageBox. Show (string. Format ("file saved successfully "));


MessageBox. Show ("cancel saving files ");


At this point, the XPS printing and display functions of fixed documents are implemented. Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.