Search code examples
c#.netwpfxps

How to Convert XpsDocument to Byte[]


What is the best way to convert System.Windows.Xps.Packaging.XpsDocument object to a byte[] ?


Solution

  • public static byte[] GenerateByteArrayFromXpsDocument()
    {
        string tempFileName = System.IO.Path.GetTempFileName();
    
        //GetTempFileName creates a file, the XpsDocument throws an exception if the file already
        //exists, so delete it. Possible race condition if someone else calls GetTempFileName
        File.Delete(tempFileName);
    
        using (XpsDocument xpsDocument = new XpsDocument(tempFileName, FileAccess.ReadWrite))
        {
             XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
             writer.Write(/* use my own way to write xps file */);  // use your own way to write write the xps file instead
        }
    
        return File.ReadAllBytes(tempFileName);
    }