public static byte [ ] getDocumentToByteArray ( Document dom ) { try { TransformerFactory tFactory = TransformerFactory . newInstance ( ) ; Transformer transformer = tFactory . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "no" ) ; transformer . setOutputProperty ( OutputKeys . METHOD , "html" ) ; // TODO should be fixed to read doctype declaration transformer . setOutputProperty ( OutputKeys . DOCTYPE_PUBLIC , "-//W3C//DTD XHTML 1.0 Strict//EN\" " + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" ) ; DOMSource source = new DOMSource ( dom ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Result result = new StreamResult ( out ) ; transformer . transform ( source , result ) ; return out . toByteArray ( ) ; } catch ( TransformerException e ) { LOGGER . error ( "Error while converting the document to a byte array" , e ) ; } return null ; }
Serialize the Document object .