Is there a way to开发者_如何学Python convert every page in a XPS document to an image programmatically using C#?
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));
}
Please refer to the accepted answer it is really helpful (it helped me also) .I just want to note to some very important point in that solution.
if you are implementing your own DocumentPaginator (as in my case) then that code will Not work because we will not get reference to your specific Paginator from the statement
DocumentPaginator paginator = seq.DocumentPaginator;
Casting this to your own paginator also will not work.
also that solution is very complex in case you have your own Paginator
.
So I developed a simplified solution , which based on the accepted solution of this question and this worked exactly as needed.
// create your own paginator instead of this
// this is my specific own implementation for DocumentPaginator class
ReportPaginator paginator = new ReportPaginator(report);
Visual visual = paginator.GetPage(0).Visual; // first page - loop for all
RenderTargetBitmap bmp = new RenderTargetBitmap((int)paginator.PageSize.Width, (int)paginator.PageSize.Height, 96d, 96d, PixelFormats.Default);
bmp.Render(visual);
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(bmp));
using (MemoryStream sm = new MemoryStream())
{
png.Save(sm);
return sm.ToArray();
}
精彩评论