如何将 XpsDocument 转换为 Byte[]

How to Convert XpsDocument to Byte[]

System.Windows.Xps.Packaging.XpsDocument 对象转换为 byte[] 的最佳方法是什么?

您可以用这种方式转换大多数对象,Xps 文档为:

BinaryFormatter binaryFormatter = new BinaryFormatter();
using(MemoryStream memoryStream = new MemoryStream())
{
    binaryFormatter.Serialize(memoryStream, anyObject);
    var result=ms.ToArray();
}
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);
}