Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert every page in a XPS file to an image in C#?

Tags:

c#

image

wpf

xps

Is there a way to convert every page in a XPS document to an image programmatically using C#?

like image 494
Kaveh Shahbazian Avatar asked Sep 25 '10 19:09

Kaveh Shahbazian


1 Answers

I ran across this blog post from Josh Twist that appears to do what you want.

Cracking an XPS in WPF

On searching the net, there are many paid/trial programs that claim to do this (I have not tried any of them, so I can't vouch/list any of them). I assumed you want to write your own code.

Here is the 'meat' of the blog post (condensed):

Uri uri = new Uri(string.Format("memorystream://{0}", "file.xps"));
FixedDocumentSequence seq;

using (Package pack = Package.Open("file.xps", ...))
using (StorePackage(uri, pack))  // see method below
using (XpsDocument xps = new XpsDocument(pack, Normal, uri.ToString()))
{
    seq = xps.GetFixedDocumentSequence();
}

DocumentPaginator paginator = seq.DocumentPaginator;
Visual visual = paginator.GetPage(0).Visual;  // first page - loop for all

FrameworkElement fe = (FrameworkElement)visual;

RenderTargetBitmap bmp = new RenderTargetBitmap((int)fe.ActualWidth,
                          (int)fe.ActualHeight, 96d, 96d, PixelFormats.Default);
bmp.Render(fe);

PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(bmp));

using (Stream stream = File.Create("file.png"))
{
    png.Save(stream);
}

public static IDisposable StorePackage(Uri uri, Package package)
{
    PackageStore.AddPackage(uri, package);
    return new Disposer(() => PackageStore.RemovePackage(uri));
}
like image 93
Edward Leno Avatar answered Oct 03 '22 23:10

Edward Leno