Create XPS documents from C# code using "Microsoft XPS Document Writer v4"
The Windows XPS Document writer provides a handy tool for generating XPS documents. However, it is require to create printer at windows otherwise printing is not possible. This article gives you a handy tool to generate XPS document using C# code.
To generate XPS document using this project you need pre generated XPS document currently I have added sample XPS document with this Project. This sample generates XPS using Microsoft XPS Document Writer v4 driver and its a part of windows installation so you do not require any extra installation.
This code is focussed around creating a virtual printer, and then sets the output location for this virtual printer to print the XPS document. It creates the output port on the "Local Port" monitor, using the "AddPortEx" API (winspool.drv) of windows32.
The VirtualPrinter
class can be used to create a virtual printer and port for that printer. After the creation of printer and port associate that port with virtual printer. When form is closed it will destroys the created printer and port and released all resources.
To use the code, simply create an instance of the VirtualPrinter
class, passing it a printer name and a filename to send the output to. Use this printer name to direct output to the specified XPS file. To create another XPS document, simply call the SetPort
method of the Virtual printer, passing it the new file name.
Click here to download sample XPSPrinter.
XPS to PDF Conversion in C#
Process process = new Process();process.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ghostxps-9.54.0-win32", "gxpswin32.exe");process.StartInfo.Arguments = $"-sDEVICE=pdfwrite -sOutputFile=\"{pdfFilePath}\" -dNOPAUSE \"{xpsFilePath}\"";process.Start();process.WaitForExit();
I have provide the sample application to convert the XPS to PDF. In this application I have used GhostXPS 9.54.0 for Windows 32. In that I have added one sample xps file to convert it to pdf but you can change the xpsFilePath as per your convenience.
Click here to download XPSToPDFConversion.
Sign up here with your email