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

This post shows you How to Convert XPS to Bitmap in C# .NET 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 drag the TextBox, Label, and Button from the visual studio toolbox to your winforn.

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 the 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 winform.

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);
            renderTarget.Render(documentPage.Visual);
            BitmapEncoder bitmapEncoder = new BmpBitmapEncoder();
            bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
            string file = Application.StartupPath + "\\xps_page" + pageCount + ".bmp";
            using (FileStream fileStream = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                bitmapEncoder.Save(fileStream);
            }
        }
    }
}

We will convert each page into a bitmap file. 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)
{
    ConvertXpsToBitmap(txtFileName.Text);
}