Search code examples
c#.netzipxps

Manipulating XPS-file as ZIP-archive using ZipFile in C#


I am trying to remove some nodes from FixedPage entries of an XPS-file. I wrote a method that operates FixedPage's xml the way I want, tested it manually by extracting *.fpage files out of xps and placing them back again. Everything seemed to be Ok. So, I developed a simple utility that processes every fixed page in an xps-file:

var arch = ZipFile.Open(xpsFileName, System.IO.Compression.ZipArchiveMode.Update);

foreach (var entry in arch.Entries)
    if (entry.Name.EndsWith(".fpage"))
    {
        var file = entry.Open();

        var page = XElement.Load(file);
        page = ProcessPage(page);

        file.Position = 0;
        page.Save(file);
        file.SetLength(file.Position);

        file.Close();
    }

arch.Dispose();

Although the resulting xps-file keeps integrity of a zip-archive and can be decompressed with unzip, 7zip, windows explorer etc, the Microsoft XPS Viewer can not display it, showing some error message ("could not open this document" or something like that). I am pretty sure the file shoud be valid xps-file. Furthermore, if I repack its contents into a new zip-file with any utility I mentioned before, and rename it to xps, it becomes posible to view its contents with MS XPS viewer. Could anyone push me into right direction or show me what I did wrong?


Solution

  • I didn't took in mind xps is actually a .net Package. I've solved my problem by using ZipPackage class:

        using (var pack = ZipPackage.Open(xpsFileName, FileMode.Open, FileAccess.ReadWrite))
        {
            foreach (var part in pack.GetParts()) if (part.Uri.OriginalString.EndsWith(".fpage"))
                {
                    using (var file = part.GetStream(FileMode.Open, FileAccess.ReadWrite))
                    {
                        var page = ProcessPage(XElement.Load(file));
                        file.Position = 0;
                        page.Save(file);
                        file.SetLength(file.Position);
                    }
                }
        }