This article shows how to serialize a Document object to obtain a byte array representing the Document and then how to unserialize the byte array to obtain a Document object again. This technique is often required when storing a document in a database or for preparing a Document for transmission across the web.
Please note that an Aspose.Words.Document object cannot be serialized using built in Java serialization techniques but instead can be serialized by using the method detailed below.
The simplest method used to serialize a Document object is to first save it to a ByteArrayOutputStream using the Document.Save(Stream, SaveFormat) method overload of the Document class. The toByteArray method is then called on the stream which returns an array of bytes representing the document in byte form.
The save format chosen is important as to ensure the highest fidelity is retained upon saving and reloading into the Document object. For this reasons an OOXML format is suggested.
The steps above are then reversed to load the bytes back into a Document object.
Example
Shows how to convert a document object to an array of bytes and back into a document object again.
[Java]
// Load the document.
Document doc = new Document(getMyDir() + "Document.doc");
// Create a new memory stream.
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// Save the document to stream.
doc.save(outStream, SaveFormat.DOCX);
// Convert the document to byte form.
byte[] docBytes = outStream.toByteArray();
// The bytes are now ready to be stored/transmitted.
// Now reverse the steps to load the bytes back into a document object.
ByteArrayInputStream inStream = new ByteArrayInputStream(docBytes);
// Load the stream into a new document object.
Document loadDoc = new Document(inStream);