如何将XpsDocument转换为字节[]

时间:2015-05-27 08:04:14

标签: c# .net wpf xps

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

2 个答案:

答案 0 :(得分:-1)

您可以通过这种方式转换大多数对象,XpsDocument:

BinaryFormatter binaryFormatter = new BinaryFormatter();
using(MemoryStream memoryStream = new MemoryStream())
{
    binaryFormatter.Serialize(memoryStream, anyObject);
    var result=ms.ToArray();
}

答案 1 :(得分:-1)

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);
}