1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$ */
// Derived from examples/embedding/java/embedding/ExampleXML2PDF.java
// in FOP-0.20.5
//Java
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Vector;
//JAXP
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;
// SAX
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ErrorHandler;
// XML Commons
import org.apache.xml.resolver.tools.CatalogResolver;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Parser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.ParseException;
//Avalon
import org.apache.avalon.framework.ExceptionUtil;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
//FOP
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
/**
* This class converts an XML file to PDF using
* JAXP (XSLT) and FOP (XSL:FO).
*/
public class BookMaker implements ErrorHandler {
private Logger logger;
private File xmlFile, xsltFile, outFile, pdfFile;
private boolean useCatalog;
private Vector xsltParams = null;
public BookMaker() {
//Setup logger
logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
}
/**
* org.xml.sax.ErrorHandler#warning
**/
public void warning(SAXParseException e) {
logger.warn(e.toString());
}
/**
* org.xml.sax.ErrorHandler#error
**/
public void error(SAXParseException e) {
logger.error(e.toString());
}
/**
* org.xml.sax.ErrorHandler#fatalError
**/
public void fatalError(SAXParseException e) throws SAXException {
logger.error(e.toString());
throw e;
}
public void makeBook()
throws IOException, FOPException, TransformerException,
FactoryConfigurationError,
ParserConfigurationException, SAXException {
OutputStream out = null;
try {
Source xmlSource, xsltSource;
Result result;
CatalogResolver resolver = null;
// Setup entity and URI resolver
if (useCatalog) {
resolver = new CatalogResolver();
logger.info("Using " + resolver.getClass().getName()
+ " as entity/URI resolver");
}
//Setup XSLT transformer
TransformerFactory tFactory = TransformerFactory.newInstance();
if (useCatalog) {
tFactory.setURIResolver(resolver);
}
//Setup input and xslt sources
if (useCatalog) {
SAXParser parser;
XMLReader xmlReader;
FileInputStream fis;
InputSource is;
// throws FactoryConfigurationError
SAXParserFactory sFactory = SAXParserFactory.newInstance();
sFactory.setNamespaceAware(true);
// Setup input source
// throws ParserConfigurationException
parser = sFactory.newSAXParser();
// throws SAXException
xmlReader = parser.getXMLReader();
logger.info("Using " + xmlReader.getClass().getName()
+ " as SAX parser");
xmlReader.setErrorHandler(this);
xmlReader.setEntityResolver(resolver);
// Setup SAX source
fis = new FileInputStream(xmlFile);
is = new InputSource(fis);
xmlSource = new SAXSource(xmlReader, is);
// Setup xslt source
// throws ParserConfigurationException
parser = sFactory.newSAXParser();
// throws SAXException
xmlReader = parser.getXMLReader();
logger.info("Using " + xmlReader.getClass().getName()
+ " as SAX parser");
xmlReader.setErrorHandler(this);
xmlReader.setEntityResolver(resolver);
// Setup SAX source
fis = new FileInputStream(xsltFile);
is = new InputSource(fis);
xsltSource = new SAXSource(xmlReader, is);
} else {
xmlSource = new StreamSource(xmlFile);
xsltSource = new StreamSource(xsltFile);
}
// Setup output result
if (pdfFile != null) {
//Setup FOP
MessageHandler.setScreenLogger(logger);
Driver driver = new Driver();
driver.setLogger(logger);
driver.setRenderer(Driver.RENDER_PDF);
out = new FileOutputStream(pdfFile);
driver.setOutputStream(out);
//Resulting SAX events (the generated FO)
// must be piped through to FOP
result = new SAXResult(driver.getContentHandler());
} else {
out = new FileOutputStream(outFile);
result = new StreamResult(out);
}
// Setup the transformer
Transformer transformer
= tFactory.newTransformer(xsltSource);
logger.info("Using " + transformer.getClass().getName()
+ " as TrAX transformer");
// Set the value of parameters, if any, defined for stylesheet
if (xsltParams != null) {
for (int i = 0; i < xsltParams.size(); i += 2) {
transformer.setParameter
((String) xsltParams.elementAt(i),
(String) xsltParams.elementAt(i + 1));
}
}
//Start XSLT transformation and FOP processing
transformer.transform(xmlSource, result);
} finally {
if (out != null) {
out.close();
}
}
}
private static Options createOptions() {
Options options = new Options();
OptionGroup og;
Option o;
o = new Option("h", "help", false, "Print help");
options.addOption(o);
o = new Option("c", "useCatalog", false, "Use catalog");
options.addOption(o);
o = new Option("xml", "xmlFile", true, "XML input file");
o.setArgName("file");
options.addOption(o);
o = new Option("xsl", "xslFile", true, "XSLT stylesheet");
o.setArgName("file");
options.addOption(o);
// mutually exclusive output options
og = new OptionGroup();
o = new Option("out", "outFile", true, "(X)HTML/FO output file");
o.setArgName("file");
og.addOption(o);
o = new Option("pdf", "pdfFile", true, "PDF output file");
o.setArgName("file");
og.addOption(o);
options.addOptionGroup(og);
o = new Option("p", "parameter", true,
"Parameter for the XSLT transformation");
o.setArgs(2);
o.setArgName("name value");
options.addOption(o);
return options;
}
public static void main(String[] args) {
BookMaker app = new BookMaker();
try {
// Setup options
Options options = createOptions();
// Parse command line
// GNU parser allow multi-letter short options
Parser parser = new GnuParser();
CommandLine cl = null;
cl = parser.parse(options, args);
if (cl.hasOption("h")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("BookMaker", options);
System.exit(0);
}
//Setup input and output files and parameters
if (cl.hasOption("c")) {
app.useCatalog = true;
}
if (cl.hasOption("xml")) {
app.xmlFile = new File(cl.getOptionValue("xml"));
}
if (cl.hasOption("xsl")) {
app.xsltFile = new File(cl.getOptionValue("xsl"));
}
if (cl.hasOption("out")) {
app.outFile = new File(cl.getOptionValue("out"));
}
if (cl.hasOption("pdf")) {
app.pdfFile = new File(cl.getOptionValue("pdf"));
}
if (cl.hasOption("p")) {
String[] params = cl.getOptionValues("p");
app.xsltParams = new Vector();
for (int i = 0; i < params.length; ++i) {
app.xsltParams.addElement(params[i]);
}
}
app.logger.info("Input: XML (" + app.xmlFile + ")");
app.logger.info("Stylesheet: " + app.xsltFile);
if (app.pdfFile != null) {
app.logger.info("Output: PDF (" + app.pdfFile + ")");
} else {
app.logger.info("Output: (X)HTML/FO (" + app.outFile + ")");
}
app.logger.info("");
app.logger.info("Transforming...");
app.makeBook();
app.logger.info("Transforming done");
} catch (Exception e) {
app.logger.error(ExceptionUtil.printStackTrace(e));
System.exit(1);
}
}
}
|