Windows Forms: How to Convert XPS to Bitmap in C#

This post shows you How to Convert XPS to Bitmap in C# Windows Forms Application.

What is an XPS file?

It stands for XML Paper Specification and is basically an electronic representation of digital documents based on XML.

Creating a new Windows Forms Application project, then open your form designer.

Next, Drag the TextBox, Label, and Button from the Visual Studio toolbox into your form designer.

You can design as simple UI allows you to select the xps file, then convert it to a bitmap file in c# as shown below.

how to convert xps to bitmap in c#

How to convert XPS file to Bitmap in C#

Adding a click event handler to the Browse button allows you to select the xps document file.

private void btnBrowse_Click(object sender, EventArgs e)
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "XPS Documents|*.xps" })
        if (ofd.ShowDialog() == DialogResult.OK)
            txtFileName.Text = ofd.FileName;

You need to add references to the libraries below

  1. WindowsBase.dll
  2. ReachFramework.dll
  3. PresentationFramework.dll
  4. PresentationCore.dll

then add include the namespace below to your form.

using System;
using System.IO;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using System.Windows.Xps.Packaging;

You need to create a ConvertXpsToBitmap method that allows you to convert xps documents into bitmap files in c#.

public void ConvertXpsToBitmap(string fileName)
    using (XpsDocument xpsDocument = new XpsDocument(fileName, FileAccess.Read))
        FixedDocumentSequence fixedDocumentSequence = xpsDocument.GetFixedDocumentSequence();
        for (int pageCount = 0; pageCount < fixedDocumentSequence.DocumentPaginator.PageCount; ++pageCount)
            DocumentPage documentPage = fixedDocumentSequence.DocumentPaginator.GetPage(pageCount);
            RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)documentPage.Size.Width, (int)documentPage.Size.Height, 96, 96, System.Windows.Media.PixelFormats.Default);
            BitmapEncoder bitmapEncoder = new BmpBitmapEncoder();
            string file = Application.StartupPath + "\\xps_page" + pageCount + ".bmp";
            using (FileStream fileStream = new FileStream(file, FileMode.Create, FileAccess.Write))

We will convert each page to a bitmap file, then save it to the debug directory. It's the same directory as your application.

Finally, Add the click event handler to the Convert button allows you to convert xps into an image file in c#.

private void btnConvert_Click(object sender, EventArgs e)