Here you can find the source of toByteArray(final Document document)
public static byte[] toByteArray(final Document document) throws IOException, TransformerException
//package com.java2s; /**/*from w w w .j av a2s .com*/ * Copyright (C) 2015 BonitaSoft S.A. * BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation * version 2.1 of the License. * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth * Floor, Boston, MA 02110-1301, USA. **/ import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class Main { public static byte[] toByteArray(final Document document) throws IOException, TransformerException { if (document == null) { throw new IllegalArgumentException("Document should not be null."); } final Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); ByteArrayOutputStream out = null; try { out = new ByteArrayOutputStream(); tf.transform(new DOMSource(document), new StreamResult(out)); return out.toByteArray(); } finally { if (out != null) { out.close(); } } } }