Author: holyfaire-mail: holyfair@sina.com
One. Preface
In some applications, we usually convert some text and configuration information into XML files to transmit, modify, save. Especially documents with a certain template nature to implement their management, it is quite convenient. Provide XML There are many Java APIs for files, such as DOM, JDOM, Castor, SAX, XMLReader, XPath, XSLT, and more. The usage of these APIs is not mentioned here. When using these interfaces, XML operation is implemented, Some documents must eventually present to the user or what we usually be familiar with Word and PDF documents. We will see the implementation of an XML file to RTF and PDF file transition.
II. From XML to PDF
For an XML file with a certain template, we can use the FOP API to achieve the conversion of PDF. FOP requires FOP.jar. We can get and understand its usage on http://xml.apache.org/fop/ Take a general complex XML file as an example: to convert the XML document Test.xml as follows:
For such an XML document, we must convert it into a PDF format to create an XSL-FO file to define the conversion to each Element and Value format. We build the XSL-FO file Test.xsl as follows:
XML Version = "1.0" encoding = "UTF-8"?>
! - ========================================00 Font-weight = "bold" space-after = "5mm" margin-left = "5mm"> 1.4. References fo: block> fo: Table-Row> XSL: for-Each> fo: Table-Body> fo: Table> fo: block> xsl: template> XSL: for-each select = "strresource"> public class ExampleXML2PDF {public void convertXML2PDF (File xml, File xslt, File pdf) throws IOException, FOPException, TransformerException {Driver driver = new Driver (); Logger logger = new ConsoleLogger (ConsoleLogger.LEVEL_INFO); driver.setLogger (logger); MessageHandler.setScreenLogger (logger); // Setup Renderer (output format) driver.setRenderer (Driver.RENDER_PDF); // Setup output OutputStream out = new java.io.FileOutputStream (pdf); try {driver.setOutputStream (out); // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance (); Transformer transformer = factory.newTransformer (new StreamSource (xslt)); // Setup input for XSLT transformation Source src = new StreamSource (xml); // Resulting SAX events (the Generated fo) Must Be Piped THROUGH to FOP RESULT RES = New Saxr Esult (Driver.getContentHandler ()); // Start Xslt Transformation and Fop Processing Transformer.Transform (src, res);} finally {out.close ();}} public static void main (string [] args) {TRY { System.out.println ("FOP EXAMPLEXML2PDF / N"); System.out.Println ("preplay ..."); // setup Director File Basedir = new file ("."); File outdir = new file (Basedir , "out"; outdir.mkdirs (); // setup input and output files file xmlfile = new file (basedir, "test.xml"); file xsltfile = New file (Basedir, "Test.xsl"); file pdffile = new file (Outdir, "Test.pdf"); system.out.println ("Input: XML (" XMLFile ")"); system.out .println ("Stylesheet:" xsltfile; system.out.println ("Output: PDF (" PDFFILE ")"); system.out.println (); system.out.println ("Transforming ... "); ExampleXML2PDF app = new ExampleXML2PDF (); app.convertXML2PDF (xmlfile, xsltfile, pdffile); System.out.println (" Success ");!} catch (Exception e) {System.err.println (ExceptionUtil.printStackTrace (e)); system.exit (-1);}}} This easily implements XML documentation to the conversion of PDF documents. If you use it in a servlet of WebService, you want to generate PDF transfer from XML files. PDF files do not generate by viewers, we can implement them as follows: public class FOPServlet extends HttpServlet {public static final String FO_REQUEST_PARAM = "fo"; public static final String XML_REQUEST_PARAM = "xml"; public static final String XSL_REQUEST_PARAM = "xsl"; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException {try {String Xmlparam = getServletContext (). GetRealPath ("Web-INF / DOC / XML / Test.xml"); String Xslparam = GetServletContext (). GetRealPath ("Web-INF / DOC / XSL / TEST.XSL"); if (!! (xmlParam = null) && (xslParam = null)) {XSLTInputHandler input = new XSLTInputHandler (new File (xmlParam), new File (xslParam)); renderXML (input, response);} else {PrintWriter out = response. getwriter (); out.println (" FOPSERVLET ERROR h1> < H3> NO 'FO' " " Request param Given. body> html> ");}} Catch (servletexception ex) {throw ex;} catch (exception ex) {throw new servletexception (ex); } public void renderXML (XSLTInputHandler input, HttpServletResponse response) throws ServletException {try {ByteArrayOutputStream out = new ByteArrayOutputStream (); response.setContentType ( "application / pdf"); Driver driver =
New Driver (); driver.render_pdf; driver.setputstream (out); driver.render (), input.getinputsource (); byte [] content = out.tobyteaRray (); response .setContentLength (content.length);. response.getOutputStream () write (content); response.getOutputStream () flush ();.} catch (Exception ex) {throw new ServletException (ex);.}}} XML to three RTF
The conversion of XML to RTF slightly has some troubles. We didn't directly from XML to RTF API, we will use the JFOR API to be integrated into the FOP. JFOR API can implement the conversion from the FO file to the RTF file, it also provides The consLle interface. We can get JFOR related information from www.jfor.org. We can divide two steps from the XML file to the RTF file: 1. Convert XML to FO 2. Use the FOP to convert FO to FO RTF 3.1 Convert XML with FOP to FO This step we can easily follow the methods described above, and the XML to FO conversions are implemented, and the XML files used above and the XSL-FO files are still used.
OutputStream foOut = new FileOutputStream (fofile); TransformerFactory factory = TransformerFactory.newInstance (); Transformer transformer = factory.newTransformer (new StreamSource (xsltfile)); Source src = new StreamSource (xmlfile); Result res = new StreamResult (foOut); Transformer.Transform (src, res); foout.close ();
3.2 Convert FO to RTF with JFOR
Take only the implementation of the server demand:
InputStream foInput = new FileInputStream (fofile); InputSource inputSource = new InputSource (foInput); ByteArrayOutputStream out = new ByteArrayOutputStream (); Writer output = new OutputStreamWriter (out); response.setContentType ( "application / msword"); new Converter (inputSource Output, converter.createconvertEn (); output.flush (); byte [] content = out.tobyteaRray (); system.out.println (out.tostring ()); response.setcontentLENGTH (Content.Length); response . GetputStream (). Write (content); response.getOutputStream (). Flush (); Foinput.close (); output.close (); out.close (); This successfully converts XML into RTF format document.
This article only provides a general implementation process, and the specific details can be referred to in detail in detail.