Pro XML Development with Java Technology 2006 phần 9 pps

63 801 0
Pro XML Development with Java Technology 2006 phần 9 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

CHAPTER 11 ■ CONVERTING XML TO SPREADSHEET, AND VICE VERSA 307 case 8: HSSFRow row8 = spreadsheet.getRow(8); Element invincome1 = document.createElement("invincome"); stmtElement1.appendChild(invincome1); invincome1.appendChild (document.createTextNode (row8.getCell((short) 1). getStringCellValue())); Element invincome2 = document.createElement("invincome"); stmtElement2.appendChild(invincome2); invincome2.appendChild (document.createTextNode (row8.getCell((short) 2). getStringCellValue())); break; case 9: HSSFRow row9 = spreadsheet.getRow(9); Element incbeforetaxes1 = document .createElement("incbeforetaxes"); stmtElement1.appendChild(incbeforetaxes1); incbeforetaxes1.appendChild (document.createTextNode (row9.getCell((short) 1). getStringCellValue())); Element incbeforetaxes2 = document.createElement("incbeforetaxes"); stmtElement2.appendChild(incbeforetaxes2); incbeforetaxes2.appendChild (document.createTextNode (row9.getCell((short)2). getStringCellValue())); break; case 10: HSSFRow row10 = spreadsheet.getRow(10); Element taxes1 = document.createElement("taxes"); stmtElement1.appendChild(taxes1); taxes1.appendChild(document.createTextNode(row10.getCell( (short) 1).getStringCellValue())); Element taxes2 = document.createElement("taxes"); stmtElement2.appendChild(taxes2); Vohra_706-0C11.fm Page 307 Tuesday, August 8, 2006 6:43 AM 308 CHAPTER 11 ■ CONVERTING XML TO SPREADSHEET, AND VICE VERSA taxes2.appendChild(document.createTextNode(row10.getCell( (short) 2).getStringCellValue())); break; case 11: HSSFRow row11 = spreadsheet.getRow(11); Element netincome1 = document.createElement("netincome"); stmtElement1.appendChild(netincome1); netincome1.appendChild(document.createTextNode(row11 .getCell((short) 1).getStringCellValue())); Element netincome2 = document.createElement("netincome"); stmtElement2.appendChild(netincome2); netincome2.appendChild(document.createTextNode(row11 .getCell((short) 2).getStringCellValue())); break; default: break; } } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); //Add indentation to output transformer.setOutputProperty (OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (IOException e) { System.out.println("IOException " + e.getMessage()); } catch (ParserConfigurationException e) { System.out .println("ParserConfigurationException " + e.getMessage()); } catch (TransformerConfigurationException e) { System.out.println("TransformerConfigurationException " + e.getMessage()); } catch (TransformerException e) { System.out.println("TransformerException " + e.getMessage()); } } Vohra_706-0C11.fm Page 308 Tuesday, August 8, 2006 6:43 AM CHAPTER 11 ■ CONVERTING XML TO SPREADSHEET, AND VICE VERSA 309 public static void main(String[] argv) { ExcelToXML excel = new ExcelToXML(); File input = new File("IncomeStatements.xls"); excel.generateXML(input); } } You can run the application ExcelToXML.java in Eclipse with the procedure explained in Chapter 1. Listing 11-16 shows the output from the ExcelToXML.java application. Listing 11-16. Output from ExcelToXML.java <?xml version="1.0" encoding="UTF-8"?> <incmstmts> <stmt> <year>2005</year> <revenue>11837</revenue> <costofrevenue>2239</costofrevenue> <researchdevelopment>1591</researchdevelopment> <salesmarketing>2689</salesmarketing> <generaladmin>661</generaladmin> <totaloperexpenses>7180</totaloperexpenses> <operincome>4657</operincome> <invincome>480</invincome> <incbeforetaxes>5137</incbeforetaxes> <taxes>1484</taxes> <netincome>3653</netincome> </stmt> <stmt> <year>2004</year> <revenue>10818</revenue> <costofrevenue>1875</costofrevenue> <researchdevelopment>1421</researchdevelopment> <salesmarketing>2122</salesmarketing> <generaladmin>651</generaladmin> <totaloperexpenses>6069</totaloperexpenses> <operincome>4749</operincome> <invincome>420</invincome> <incbeforetaxes>5169</incbeforetaxes> <taxes>1706</taxes> <netincome>3463</netincome> </stmt> </incmstmts> Summary The Apache POI API provides a useful mechanism for converting data between XML and spreadsheets. In this chapter, you learned how to convert an example XML document to an Excel spreadsheet and then convert the spreadsheet to an XML document. With XML being a universal format, there really is no limit to what you can do with it! Vohra_706-0C11.fm Page 309 Tuesday, August 8, 2006 6:43 AM Vohra_706-0C11.fm Page 310 Tuesday, August 8, 2006 6:43 AM 311 ■ ■ ■ CHAPTER 12 Converting XML to PDF In the previous chapter, we discussed the procedure to convert an XML document to a Microsoft Excel spreadsheet. In this chapter, we will show how to convert an XML document to a PDF document. The open source Apache Formatting Objects Processor (FOP) project provides an API to convert an XML document to PDF or other formats such as Printer Control Language (PCL), PostScript (PS), Scalable Vector Graphics (SVG), XML, Print, Abstract Window Toolkit (AWT), Maker Interchange Format (MIF), or TXT. You can also set the layout and font with the Apache FOP API. The Apache FOP takes an XSL formatting object (an XSL-FO object) as input and produces a PDF (or other format) document as output. XSL-FO is defined in the XSL 1.0 specification. 1 Therefore, to convert XML to PDF, you first need to convert XML to XSL-FO and subsequently convert XSL-FO to PDF. Installing the Software Before you can set up your project, you need to download the Apache FOP 2 zip file fop-0.20.5-bin.zip and extract the zip file to a directory. Assuming <FOP> is the directory in which you extracted the FOP zip file, you need the JAR files listed in Table 12-1 for developing an XML to PDF conversion application. You also need to download JDK 5.0. (You can also use another version of the JDK such as 1.4 or 6.0.) 1. See http://www.w3.org/TR/xsl/. 2. For more information about Apache FOP, see http://xmlgraphics.apache.org/fop/. Table 12-1. Apache FOP JAR Files JAR File Description <FOP>/build/fop.jar FOP API classes <FOP>/lib/avalon-framework-cvs-20020806.jar Logger classes <FOP>/lib/batik.jar Graphics classes <FOP>/lib/xercesImpl-2.2.1.jar The Xerces API <FOP>/lib/xml-apis.jar The XML API <FOP>/lib/xalan-2.4.1.jar The XSLT API Vohra_706-0C12.fm Page 311 Saturday, July 29, 2006 6:20 AM 312 CHAPTER 12 ■ CONVERTING XML TO PDF Setting Up the Eclipse Project To compile and run the code examples, you will need an Eclipse project. You can download project Chapter12 from the Apress website (http://www.apress.com) and import it into your Eclipse work- space by selecting File ➤ Import. The Chapter12 project consists of a com.apress.pdf package and the Java class XMLToPDF.java in the package. The XMLToPDF.java application performs the XML to PDF conversion. The Chapter12 project also consists of an example XML document (catalog.xml in Listing 12-1) and an example XSLT style sheet (catalog.xslt in Listing 12-2). To compile and run the XML to PDF code example, you need some Apache FOP JAR files in your project’s Java build path; Figure 12-1 shows these JAR files. You also need to set the JRE system library to JRE 5.0, as shown in Figure 12-1. Figure 12-1. Chapter12 Java build path Figure 12-2 shows the Chapter12 project directory structure. Vohra_706-0C12.fm Page 312 Saturday, July 29, 2006 6:20 AM CHAPTER 12 ■ CONVERTING XML TO PDF 313 Figure 12-2. Chapter12 Project directory structure Converting an XML Document to XSL-FO An XSL-FO formatting object includes formatting information about the data to be presented in a PDF document, the layout and fonts used in the document, and the tables in the document. To convert an XML document to a PDF document, first you need to convert the XML document to an XSL-FO document. The procedure to convert an XML document to an XSL-FO document is as follows: 1. Create an XSLT to transform XML to XSL-FO. 2. Set the parser and transformer system properties. 3. Create a Document object from the XML document. 4. Create a Transformer object. 5. Transform the XML document to an XSL-FO document. An XSL-FO document is in the FO namespace. Therefore, an XSL-FO document includes a namespace declaration, xmlns:fo=http://www.w3.org/1999/XSL/Format, in the root element fo:root. Table 12-2 lists some of commonly used elements in an XSL-FO document. Table 12-2. XSL-FO Elements Element Attributes Subelements Description fo:root xmlns:fo fo-layout-master-set, fo-page-sequence Root element in an XSL-FO document fo:layout-master-set fo:simple-page-master Consists of a set of page masters (at least one page master is required) fo:simple-page-master margin-right, margin-left, margin-bottom, margin-top, page-width, page-height, master-name fo:region-body Specifies page layout Vohra_706-0C12.fm Page 313 Saturday, July 29, 2006 6:20 AM 314 CHAPTER 12 ■ CONVERTING XML TO PDF The DTD for the XSL-FO object is available from http://www.renderx.com/Tests/validator/ fo2000.dtd.html. In this section, we will show how to convert an example XML document, catalog.xml, to an XSL-FO document using XSLT. Listing 12-1 shows the example XML document, catalog.xml. Listing 12-1. catalog.xml <?xml version="1.0" encoding="UTF-8"?> <catalog> <journal> <section>Java Technology</section> <publisher>IBM developerWorks</publisher> <level>Introductory</level> <edition>Nov-2004</edition> <title>Getting started with enumerated types</title> <author>Brett McLaughlin</author> </journal> <journal> <section>Java Technology</section> fo:page-sequence master-reference fo:title, fo:static-content, fo:flow Specifies the order of page masters fo:flow flow-name fo:block Page content fo:block space-before, space-after, font-weight, font-size fo:table, fo:list-block Base element for page content; includes formatting information. fo:list-block provisional-distance- between-starts, provisional-label-separation fo:list-item Specifies a block that includes a list fo:list-item text-indent fo:list-item-label, fo:list-item-body Specifies a list item fo:table border-spacing, table-layout fo:table-column, fo:table-header, fo:table-body Specifies a table in a page fo:table-column column-number, column-width Column in a table fo:table-header fo:table-row Table header fo:table-body table-layout fo:table-row Table rows fo:table-row font-weight fo:table-cell Row in a table fo:table-cell column-number fo:block Row cell that has the text of a row cell Table 12-2. XSL-FO Elements (Continued) Element Attributes Subelements Description Vohra_706-0C12.fm Page 314 Saturday, July 29, 2006 6:20 AM CHAPTER 12 ■ CONVERTING XML TO PDF 315 <publisher>IBM developerWorks</publisher> <level>Intermediate</level> <edition>Sep-2004</edition> <title>Migrating to Eclipse</title> <author>David Gallardo</author> </journal> <journal> <section>Java Technology</section> <publisher>IBM developerWorks</publisher> <level>Intermediate</level> <edition>Jan-2004</edition> <title>Design service-oriented architecture frameworks with J2EE technology</title> <author>Naveen Balani</author> </journal> </catalog> The Apache FOP API generates a PDF document from an XSL-FO document. The PDF docu- ment presents the XML document data in the form of a table. Therefore, you first need to convert the example XML document to an XSL-FO document using XSLT. An XSLT style sheet that converts XML to XSL-FO retrieves data from the XML document and, using elements in the XSL-FO namespace, creates a formatting object representation of the XML data. (Table 12-2 discussed the XSL-FO namespace elements.) Listing 12-2 shows the example XSLT document, catalog.xslt, to convert the example document to an XSL-FO document. Listing 12-2. catalog.xslt <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" exclude-result-prefixes="fo"> <xsl:output method="xml" version="1.0" omit-xml-declaration="no" indent="yes"/> <! ========================= > <! root element: catalog > <! ========================= > <xsl:template match="/catalog"> <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"> <! Setting up the Font and the Pages > <fo:layout-master-set> <fo:simple-page-master master-name="simpleA4" page-height="29.7cm" page-width="75cm" margin-top="2cm" margin-bottom="2cm" margin-left="5cm" margin-right="5cm"> <fo:region-body/> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="simpleA4"> <fo:flow flow-name="xsl-region-body"> <fo:block font-size="40pt" font-weight="bold" text-align="center" space-after="5mm"> Catalog </fo:block> <fo:block font-size="25pt"> Vohra_706-0C12.fm Page 315 Saturday, July 29, 2006 6:20 AM 316 CHAPTER 12 ■ CONVERTING XML TO PDF <fo:table table-layout="fixed"> <fo:table-column column-width="10cm"/> <fo:table-column column-width="10cm"/> <fo:table-column column-width="10cm"/> <fo:table-column column-width="10cm"/> <fo:table-column column-width="10cm"/> <fo:table-column column-width="10cm"/> <! Setting up the header > <fo:table-header> <fo:table-row font-weight="bold"><fo:table-cell> <fo:block> <xsl:text>Section</xsl:text> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <xsl:text>Publisher</xsl:text> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <xsl:text>Level</xsl:text> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <xsl:text>Edition</xsl:text> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <xsl:text>Title</xsl:text> </fo:block> </fo:table-cell> <fo:table-cell> <fo:block> <xsl:text>Author</xsl:text> </fo:block> </fo:table-cell> </fo:table-row> </fo:table-header> <fo:table-body> <! Calling template to add data from XML document to XSL-FO Table > <xsl:apply-templates select="journal"/> </fo:table-body> </fo:table> </fo:block> </fo:flow> </fo:page-sequence> <! End of root element of XSL-FO document > </fo:root> Vohra_706-0C12.fm Page 316 Saturday, July 29, 2006 6:20 AM [...]... Saturday, July 29, 2006 6:20 AM CHAPTER 12 ■ CONVERTING XML TO PDF Listing 12 -9 XMLToPDF .java package com.apress.pdf; import import import import import import import import import import org.apache.fop.apps.*; org.apache.avalon.framework.logger.*; java. io.*; org .xml. sax.InputSource; javax .xml. parsers.*; org .xml. sax.*; org.w3c.dom.*; javax .xml. transform.*; javax .xml. transform.dom.*; javax .xml. transform.stream.*;... Ajax programming with Java, check out Pro Ajax with Java Frameworks by Nathaniel T Schutta and Ryan Asleson (Apress, 2006) 1 The seminal article on Ajax is available at http://adaptivepath.com/publications/essays/archives/ 000385.php 3 29 Vohra_706-0C13.fm Page 330 Saturday, July 29, 2006 5:45 AM 330 CHAPTER 13 ■ BUILDING WEB APPLICATIONS WITH AJAX What Is XMLHttpRequest? The XMLHttpRequest object provides... (org.apache.fop.apps.FOPException e) { System.out.println(e.getMessage()); } } public static void main(String[] argv) { XMLToPDF xmlToPDF = new XMLToPDF(); File xmlFile = new File("catalog .xml" ); File xsltFile = new File("catalog.xslt"); xmlToPDF.generateXSLFO(xmlFile, xsltFile); xmlToPDF.generatePDF(); } } Vohra_706-0C12.fm Page 325 Saturday, July 29, 2006 6:20 AM CHAPTER 12 ■ CONVERTING XML TO PDF You... July 29, 2006 6:20 AM 318 CHAPTER 12 ■ CONVERTING XML TO PDF Listing 12-3 Setting System Properties System.setProperty("javax .xml. parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); System.setProperty ("javax .xml. transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl"); Creating a Document You can create a Document object by parsing an XML. .. the XMLHttpRequest object is a window object property and act accordingly, as shown in Listing 13-7 Listing 13-7 Creating an XMLHttpRequest Object function validateCatalogId(){ var xmlHttpRequest=init(); Vohra_706-0C13.fm Page 3 39 Saturday, July 29, 2006 5:45 AM CHAPTER 13 ■ BUILDING WEB APPLICATIONS WITH AJAX function init(){ if (window.XMLHttpRequest) { return new XMLHttpRequest();... In the JavaScript function validateCatalogId(), you need to create a new XMLHttpRequest object If a browser supports the XMLHttpRequest object as an ActiveXObject object, the procedure to create an XMLHttpRequest object is different when the XMLHttpRequest object is a window object property IE 7 and Netscape support XMLHttpRequest as a window property, and IE 6 supports the XMLHTTPRequest object... target deletes the project directories Listing 13-4 shows the build .xml file Listing 13-4 build .xml . java. io.*; import org .xml. sax.InputSource; import javax .xml. parsers.*; import org .xml. sax.*; import org.w3c.dom.*; import javax .xml. transform.*; import javax .xml. transform.dom.*; import javax .xml. transform.stream.*; public. 29, 2006 6:20 AM CHAPTER 12 ■ CONVERTING XML TO PDF 323 Listing 12 -9. XMLToPDF .java package com.apress.pdf; import org.apache.fop.apps.*; import org.apache.avalon.framework.logger.*; import java. io.*; import. Chapter12 project consists of a com.apress.pdf package and the Java class XMLToPDF .java in the package. The XMLToPDF .java application performs the XML to PDF conversion. The Chapter12 project

Ngày đăng: 06/08/2014, 08:22

Từ khóa liên quan

Mục lục

  • Pro XML Development with JavaTM Technology

    • PART 5 Utilities

      • Chapter 12 Converting XML to PDF

      • PART 6 Web Applications and Services

        • Chapter 13 Building Web Applications with Ajax

        • Chapter 14 Building XML-Based Web Services

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan