This example shows you How to convert XPS file to Bitmap in C# .NET.

What is an XPS file?

XPS file like a PDF file. It stands for XML Paper Specification and is basically an electronic representation of digital documents based on XML.

How to convert XPS file to Bitmap in C#

You need to add references to the libraries below.

  • WindowsBase.dll
  • ReachFramework.dll
  • PresentationFramework.dll
  • PresentationCore.dll

by right-clicking on your project, then select these files from the Assemblies->Framework item.

public void ConvertXpsToBmp(string fileName)
{
    using (XpsDocument xpsDocument = new XpsDocument(fileName, FileAccess.Read))
    {
        FixedDocumentSequence sequence = xpsDocument.GetFixedDocumentSequence();
        for (int pageCount = 0; pageCount < sequence.DocumentPaginator.PageCount; ++pageCount)
        {
            DocumentPage page = sequence.DocumentPaginator.GetPage(pageCount);
            RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)page.Size.Width, (int)page.Size.Height, 96, 96, System.Windows.Media.PixelFormats.Default);
            renderTarget.Render(page.Visual);
            BitmapEncoder encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(renderTarget));
            FileStream fStream = new FileStream(@"d:\\xps_image" + pageCount + ".bmp", FileMode.Create, FileAccess.Write);
            encoder.Save(fStream);
            fStream.Close();
        }
    }
}

Next, Create a ConvertXpsToBmp method allows you to convert from a xps file to an image file.

And don't forget to include the namespaces below.

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

Finally, call the ConvertXpsToBmp method to convert xps file to image file in c#.

string fileName = "c:\\dotnet-example.xps";
ConvertXpsToBmp(fileName);

You can create a new windows forms project, then drag the button from the visual studio toolbox to your winform.

Next, Add a click event handler to the Button that allows you to convert the xps file into a bitmap file in c# .net

Run your project, you can see that each page is a bitmap file.