Search code examples
c#.netwpfdocumentviewerxpsdocument

Load XPS to documentviewer from embedded resource


i am trying to make help for my application. I have xps documents which i am loading to documentviewer. These files are embedded in resource file.

I am able to access these as bytearray. For example Properties.Resources.help_sudoku_methods_2 returns byte[]

However, documentviewer cant read it and requires fixeddocumentsequence. So i create memory stream from bytearray, then xpsdocument and then fixeddocumentsequence like this:

 private void loadDocument(byte[] sourceXPS)
        {
            MemoryStream ms = new MemoryStream(sourceXPS);
            const string memoryName = "memorystream://ms.xps";
            Uri memoryUri = new Uri(memoryName);
            try
            {
                PackageStore.RemovePackage(memoryUri);
            }
            catch (Exception)
            { }

            Package package = Package.Open(ms);


            PackageStore.AddPackage(memoryUri, package);

            XpsDocument xps = new XpsDocument(package, CompressionOption.SuperFast, memoryName);

            FixedDocumentSequence fixedDocumentSequence = xps.GetFixedDocumentSequence();
            doc.Document = fixedDocumentSequence;


        }

This is very unclean aproach and also doesnt work if there are images in files - instead of images in new documents displays images from first loaded doc.

Is there any cleaner way to load XPS from embedded resources to documentviewer? or do i need somethink like copy file from resources to application directory and load from here and not memorystream? Thank you.


Solution

  • why dont you write file to system temp folder and then read from there.

        Stream ReadStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("file1.xps");
            string tempFile = Path.GetTempPath()+"file1.xps"; 
            FileStream WriteStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write);
            ReadStream.CopyTo(WriteStream);
            WriteStream.Close();
            ReadStream.Close();
    
            // Read tempFile INTO memory here and then
    
            File.Delete(tempFile);