如何将XPS文件中的每个页面转换为C#中的图像?

Kav*_*ian 8 c# wpf image xps

有没有办法使用C#以编程方式将XPS文档中的每个页面转换为图像?

Edw*_*eno 11

我跑过Josh Twist的这篇博文,似乎可以做你想做的事.

破解WPF中的XPS

在搜索网络时,有许多付费/试用程序声称这样做(我没有尝试过任何一个,所以我不能保证/列出其中任何一个).我以为你想编写自己的代码.

这是博客文章的"肉"(浓缩):

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));
}
Run Code Online (Sandbox Code Playgroud)

  • 如果文档在磁盘上,则不需要包存储内容.只需使用带有文件路径的构造函数重载创建一个XpsDocument,然后跳到`GetFixedDocumentSequence()`并从那里开始. (4认同)