Is there a way to convert every page in a XPS document to an image programmatically using C#?
+1
A:
I ran across this blog post from Josh Twist that appears to do what you want.
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));
}
Edward Leno
2010-09-25 23:36:47
Thankyou very much! This is exactly what I'v wanted; and I have used it and it works! Thanks again!
Kaveh Shahbazian
2010-09-26 08:16:13
Excellent, glad it helped.
Edward Leno
2010-09-26 14:20:22