XML file to RTF and PDF conversion

xiaoxiao2021-03-06  104

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:

objective here scope here responsibilities here reference here Term here definition here

summary here Breakdown here content here. content2 here. featureInteractions here estring here resourceid here rqmt here.

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:

cardiac feature srs < XSL: APPLY-TE Mplates /> <

! - ========================================00 1. Intruction 1.1 Objective 1.2 Scope 1.3. Responsibilities

Font-weight = "bold" space-after = "5mm" margin-left = "5mm"> 1.4. References 1.5. definitions, acronyms, and abbreviations < XSL: Text> Term definition < / fo: block>

2. General Description 2.1. Feature Name 2.1.1. Feature Summary 2.1.2. Feature Breakdown 2.2. feat Ure Requirements 2.3. Feature Interactions 3. String resources English string Resource ID RQMT < / fo: block> <

XSL: for-each select = "strresource"> The syntax of its specific XSL-FO file format can refer to Some other information. After the establishment of this file, we can use some of the interfaces provided by FOP to convert. FOP provides XML-> FO, XML-> PDF, FO-PDF, Obj-> fo, Obj- > PDF conversion interface. We here use XML-> PDF as an example, the rest can refer to the corresponding DEMO in the FOP package.

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 (" error </ title> </ head> / n" "<body> <H1> 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 =</p> <p>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</p> <p>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.</p> <p>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 ();</p> <p>3.2 Convert FO to RTF with JFOR</p> <p>Take only the implementation of the server demand:</p> <p>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.</p> <p>This article only provides a general implementation process, and the specific details can be referred to in detail in detail.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-103259.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="103259" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.046</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'AG9NSVCZXCucpX7_2ButJbGxnCQ0yEskM8CoM1yf1vqan2psdeuXR6hc2y80KyrdtPM5Pvez1Fe9kmdaph9HFFDw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>