1 /*
2  * $Id$
3  *
4  * Copyright 2007 Bruno Lowagie.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  */
20 
21 package com.lowagie.rups.model;
22 
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 import java.io.OutputStream;
27 
28 import org.dom4j.Document;
29 import org.dom4j.DocumentException;
30 import org.dom4j.io.OutputFormat;
31 import org.dom4j.io.SAXReader;
32 import org.dom4j.io.XMLWriter;
33 
34 import com.lowagie.rups.io.OutputStreamResource;
35 
36 /** Class that deals with the XFA file that can be inside a PDF file. */
37 public class XfaFile implements OutputStreamResource {
38 
39 	/** The X4J Document object (XML). */
40 	protected Document xfaDocument;
41 
42 	/**
43 	 * Constructs an XFA file from an OutputStreamResource.
44 	 * This resource can be an XML file or a node in a RUPS application.
45 	 * @param	resource	the XFA resource
46 	 * @throws IOException
47 	 * @throws DocumentException
48 	 */
XfaFile(OutputStreamResource resource)49 	public XfaFile(OutputStreamResource resource) throws IOException, DocumentException {
50 		// Is there a way to avoid loading everything in memory?
51 		// Can we somehow get the XML from the PDF as an InputSource, Reader or InputStream?
52 		ByteArrayOutputStream baos = new ByteArrayOutputStream();
53 		resource.writeTo(baos);
54 		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
55 		SAXReader reader = new SAXReader();
56 		xfaDocument = reader.read(bais);
57 	}
58 
59 	/**
60 	 * Getter for the XFA Document object.
61 	 * @return	a Document object (X4J)
62 	 */
getXfaDocument()63 	public Document getXfaDocument() {
64 		return xfaDocument;
65 	}
66 
67 	/**
68 	 * Writes a formatted XML file to the OutputStream.
69 	 * @see com.lowagie.rups.io.OutputStreamResource#writeTo(java.io.OutputStream)
70 	 */
writeTo(OutputStream os)71 	public void writeTo(OutputStream os) throws IOException {
72 		if (xfaDocument == null)
73 			return;
74 		OutputFormat format = new OutputFormat("   ", true);
75         XMLWriter writer = new XMLWriter(os, format);
76         writer.write(xfaDocument);
77 	}
78 }
79