Download XF Rendering Server 2007 Java Tutorial and QuickStarts

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
XF Rendering Server 2007 Java Tutorial and
QuickStarts
Copyright© 2002-2006 ECRION Software. All Rights Reserved.
This document is designed to quickly acquaint Java programmers with the programming
model of XF Rendering Server 2007 Java SDK (Software Development Kit).
Please contact Technical Support at [email protected] if you need additional information
about this product, or visit our Web Site at www.ecrion.com.
Table of Contents
About XF Rendering Server 2007 .............................................................................. 2
Product Features ................................................................................................ 2
Before You Get Started ... ........................................................................................ 2
Platform Requirements ........................................................................................ 2
Feedback and Support ............................................................................................. 2
XF Rendering Server 2007 Java Tutorial .................................................................... 3
Hello World! ....................................................................................................... 4
XSL Transformations ........................................................................................... 5
In Memory Operations ......................................................................................... 6
Selective Rendering and Thumbnails ..................................................................... 7
Using XF Merge Contexts ..................................................................................... 8
Print ................................................................................................................. 9
Last updated: August 2006
Important Notice: This document and the information within is furnished “as is” and is
subject to change without notice. In no event shall the author be liable for any damages
whatsoever (including, without limitation, damages for loss of business profits, business
interruption, loss of business information, or any other pecuniary loss) arising out of the use
of or inability to use this product, even if the author has been advised of the possibility of
such damages.
This document was generated using XF Rendering Server 2007. For the latest version, visit
Technical Resources section on our web site.
Ecrion
Chapter 1: About XF Rendering Server 2007
About XF Rendering Server 2007
XF Rendering Server 2007 is a highly scalable, enterprise class rendering product. It can
be used to automate the creation of electronic documents like technical manuals, brochures,
proposals, business reports containing charts and graphs, by dynamically generating them
from XML.
XF Rendering Server 2007 supports two major industry standards: XSL-FO (Extensible
Style Language Formatting Objects) describing how an XML document should be formatted
for a variety of media as well as SVG (Scalable Vector Graphics) used to describe twodimensional vector and mixed vector/raster graphics in XML.
In addition, high quality, all-purpose charts can be generated directly from XML using
xChart XML language. More information can be found in xChart 1.0 Language Reference.
Product Features
•
•
•
•
Supports XSL-FO, SVG, WordML, xChart as input.
Produces PDF, Postscript, HTML, GIF, JPEG, PNG, BMP, TIFF, AFP and other formats.
Supports TrueType and Postscript Type 1 font embedding.
Scalable server architecture that can run across multiple CPUs, meeting the highperformance needs of your applications.
• Available in 32 bit and 64 bit editions.
• Is accessible from a multitude of development environments: C++, VB, ASP, Java,
Java.
• Includes XF Designer 2004 XSL-FO authoring tool.
Before You Get Started ...
In order to compile the samples you must have JDK Java compiler instaled.
Platform Requirements
XF Rendering Server 2007 can be used in the Microsoft Windows® 2000 Professional and
Server, Windows XP (32 and 64 bit) and Windows Server 2003 (32 and 64 bit)
environments.
• Minimum Intel Pentium III, AMD Athlon 500 MHz or better. Intel Pentium IV 2.4 GHz
recommended for development computers, dual XEON 3.0 GHz for production servers.
• Minimum 128 Mb RAM, 512 Mb recommended for development computers, 1Gb for
productions servers.
Feedback and Support
Copyright© 2002-2006 ECRION Software. All Rights Reserved.
Page 2 of 10
Ecrion
Send error reports, feature requests, and comments about the SDK documentation or
samples directly to the Technical Support team.
Further information about support options can be found on the Ecrion Web site.
Chapter 4: XF Rendering Server 2007 Java Tutorial
XF Rendering Server 2007 Java Tutorial
The tutorial provides a step-by-step introduction to fundamental areas of programming
using the XF Rendering Server 2007.
Java samples are included when you install the product. The location of the samples has a
path similar to the following. Here, it is assumed that C: is the XF Rendering Server 2007
installation drive:
C:\Program Files\Ecrion Software\XF Rendering Server 2007\Code Samples\
The tutorial includes the following sections:
Hello World!
Demonstrates the basic code needed to create a console
application using the Java Environment and generate a PDF
document.
XSL Transformations
Demonstrates how to transform XML using a stylesheet and
then feed this input into the rendering engine.
In Memory Operations
Demonstrates how to receive rendering output in a memory
stream.
Selective Rendering and
Thumbnails
Demonstrates how to generate thumnails and render pages
selectively.
Using Merge Contexts
Describes how to render multiple input documents into one
output.
Print
Describes how to print documents.
Ecrion
Copyright© 2002-2006 ECRION Software. All Rights Reserved.
Page 3 of 10
Chapter 4: XF Rendering Server 2007 Java Tutorial
Hello World!
The following console program is the PDF version of the traditional "Hello World!" program,
which displays the string Hello World!.
import com.ecrion.xf.*;
public class HelloWorld{
public static void main(String args[])
{
try
{
XFEngine engine = new XFEngine();
engine.render(
"<fo:root xmlns:fo='http://www.w3.org/1999/XSL/Format'>" +
"<fo:layout-master-set>" +
"<fo:simple-page-master master-name='all-pages'>" +
"<fo:region-body region-name='xsl-region-body' margin='0.7in'/>" +
"</fo:simple-page-master>" +
"</fo:layout-master-set>" +
"<fo:page-sequence master-reference='all-pages'>" +
"<fo:flow flow-name='xsl-region-body'>" +
"<fo:block>Hello World!</fo:block>" +
"</fo:flow>" +
"</fo:page-sequence>" +
"</fo:root>", "C:\\HelloWorld.pdf");
System.out.println("Document rendered successfully!\n");
}
catch (Exception e)
{ // Report any errors that may occur
System.out.println(e);
}
}
}
The complete source code for this example is located in the installation folder,
under Code Samples/Java/HelloWorld.
The method render accepts a string or InputStream derivative object as input. For output,
use a string (denoting a file name), OutputStream derivative object. There is also another
method called renderUrl if the document you want converted to PDF resides in a file.
Copyright© 2002-2006 ECRION Software. All Rights Reserved.
Page 4 of 10
Ecrion
The important points of this program are the following:
• To use the XFEngine class which is the engine for rendering documents you must
import com.ecrion.xf package. To be able to do this you must add to the CLASSPATH
environment variable the path to this package witch is by default located in the Ecrion
Software/XF Rendering Server 2007/Java folder. You have also in the Code
Samples/Java folder a HelloWorld.bat that does this for you. Also HelloWorld.bat will
execute the above example. This instructions stands for all code samples and also for
all other programs that may use the ecrion.com.xf package. The path to this package
could be added only once to the CLASSPATH variable.
• A XFEngine object is created.
• We call render, supplying an XSL-FO text and an output file name.
Remarks
When rendering in a file, the output format can be derived from the file's extension (in this
case is PDF) if is not specified explicitly using setOutputFormat/getOutputFormat accesors.
Chapter 4: XF Rendering Server 2007 Java Tutorial
XSL Transformations
One typical usage scenario is when you have a stylesheet (XSL) file, and you want to use-it
to transform input XML into XSL-FO or XCHART and then generate PDF documents or JPG
images.
In this example you must add as parameters the input xml and xsl file. The result will be
the Result.fo file located on the C: drive. XF Designer 2004 can be used to test
transformation results and preview the generated PDFs (just open the XML, and hit F5).
import
import
import
import
import
import
javax.xml.transform.Source;
javax.xml.transform.Transformer;
javax.xml.transform.TransformerFactory;
javax.xml.transform.stream.StreamSource;
javax.xml.transform.stream.StreamResult;
java.io.*;
//This example ilustrates how to create a XSLFO file from an XML and a style sheet
XSL
//The result will be an .FO etension file
public class XSLTransformations
{
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println(
"Usage: java XSLTransformations [xmlfile] [xsltfile]");
return;
}
File xmlFile = new File(args[0]);
File xsltFile = new File(args[1]);
// JAXP reads data using the Source interface
Source xmlSource = new StreamSource(xmlFile);
Source xsltSource = new StreamSource(xsltFile);
// the factory pattern supports different XSLT processors
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(xsltSource);
//transform the .fo result into a memory stream
ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
trans.transform(xmlSource, new StreamResult(memoryStream));
byte [] documentBytes = memoryStream.toByteArray();
//transfer the .fo result into a disk file
FileOutputStream fos = new FileOutputStream("C:\\Result.fo");
fos.write(documentBytes);
}
}
The complete source code for this example is located in the installation folder,
under Code Samples/Java/XSLTransformations.
Copyright© 2002-2006 ECRION Software. All Rights Reserved.
Page 5 of 10
Ecrion
The important points of this program are the following:
• First, we create and load two documents: the input XML and the stylesheet.
• Transform the xml and xsl files into a stream sources.
• With TransformerFactory we transform the xsl and xml into an XSL-FO document.
Chapter 4: XF Rendering Server 2007 Java Tutorial
In Memory Operations
In memory only operations are useful in certain special situations like storing the generated
PDFs in a database BLOB, performing additional post-processing, etc.
The example below shows one way to create an in memory stream and then use it as
output destination for the rendering process.
import com.ecrion.xf.*;
import java.io.*;
public class InMemoryRendering
{
public static void main(String args[])
{
try
{
XFEngine engine = new XFEngine();
//Renders the result into a stream in memory
ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
// The output format must be specified when rendering into a Stream.
engine.setOutputFormat(XFEngine.XOF_PDF);
// Render some XSL-FO text and place the output into our stream
engine.render(
"<fo:root xmlns:fo='http://www.w3.org/1999/XSL/Format'>" +
"<fo:layout-master-set>" +
"<fo:simple-page-master master-name='all-pages'>" +
"<fo:region-body region-name='xsl-region-body' margin='0.7in'/>" +
"</fo:simple-page-master>" +
"</fo:layout-master-set>" +
"<fo:page-sequence master-reference='all-pages'>" +
"<fo:flow flow-name='xsl-region-body'>" +
"<fo:block>Hello World!</fo:block>" +
"</fo:flow>" +
"</fo:page-sequence>" +
"</fo:root>", memoryStream);
//Do something useful with the stream
//The bytes stored in memory
byte [] documentBytes = memoryStream.toByteArray();
//Write the bytes into a file
FileOutputStream fos = new FileOutputStream("c:\\InMemoryRendering.pdf");
fos.write(documentBytes);
fos.close();
memoryStream.close();
}
}
}
The complete source code for this example is located in the installation folder,
under Code Samples/Java/InMemoryRendering.
The important points of this program are the following:
• We create a memory stream (ByteArrayOutputStream) for storing the document.
• Output format must be set before calling render.
Copyright© 2002-2006 ECRION Software. All Rights Reserved.
Page 6 of 10
Ecrion
System.out.println("Document rendered successfully!\n");
}
catch (Exception e)
{ // Report any errors that may occur
System.out.println(e);
}
Chapter 4: XF Rendering Server 2007 Java Tutorial
• Call render passing the stream as the second parameter.
Remarks
Be aware that using this feature for large documents (>1MB) can result in poor performance
if the sever doesn't have enough memory - the operating system will swap memory pages
to disk in order to accommodate your memory requests.
Selective Rendering and Thumbnails
XF Rendering Server 2007 also offers support for selective rendering of document's pages,
as well as resizing the output. You can use theese features to generate thumbnails, as
shown below:
import com.ecrion.xf.*;
public class Thumbnail
{
public static void main(String args[])
{
XFDocument doc = new XFDocument();
try
{
doc.loadUrl("http://www.ecrion.com/XF/Examples/XSLExampleMulticolumn.xml");
if (doc.getPageCount() > 0)
{
double width = doc.getPageWidth(0);
double height = doc.getPageHeight(0);
double zoom;
double thumbSize = 256;
if (thumbSize/width < thumbSize/height)
zoom = thumbSize/width*100.0;
else
zoom = thumbSize/height*100.0;
doc.setOutputFormat(XFDocument.XOF_Bitmap);
doc.setProperty("Compression", 100);
doc.setProperty("Zoom", zoom);
doc.setProperty("Pages", "0");
doc.exportTo("c:\\TestPage0.bmp");
doc.setProperty("Pages", "1");
doc.exportTo("c:\\TestPage1.bmp");
}
}
catch(Exception e)
{
// Report any errors that may occur
System.out.println(e);
}
finally
{
doc.dispose(); // XFDocuments must aways be disposed properly!
}
}
}
The important points of this program are the following:
• Document is loaded with loadUrl (or load). The url in the code exists but can be any
url.
• Once the document is loaded, you can find the number of pages, as well as the
dimensions of each individual page.
• Use exportTo to generate the output. You can call this method multiple times, for
example to generate a thumbnail for each page, or to generate the document and a
thumbnail of the first page, etc.
Copyright© 2002-2006 ECRION Software. All Rights Reserved.
Page 7 of 10
Ecrion
The complete source code for this example is located in the installation folder,
under Code Samples/Java/Thumbnail.
Chapter 4: XF Rendering Server 2007 Java Tutorial
Using XF Merge Contexts
XF can render multiple input documents into one output file or stream.
This feature can very useful for printing jobs which require all inputs to be sent to a printer
into one large file Postscript file. It can also be used for archiving purposes.
The following code fragment exemplifies this feature:
import com.ecrion.xf.*;
public class MergeOfMultipleFoDocuments
{
public static void main(String args[])
{
if (args.length<2)
{
System.out.println(args.length);
System.out.println("The first arguments represent the paths to the files that
will be merged");
System.out.println("The last argument represents the result file");
return;
}
XFMergeContext ctx = new XFMergeContext();
XFDocument doc=new XFDocument();
try
{
//Setting the Merge Context
//For merging putposes the output must be PDF or POSTSCRIPT only
ctx.setOutputFormat(XFMergeContext.XOF_PDF);
ctx.setOutput(args[args.length-1]);
for (int i=0; i<args.length-1; i++)
{
//merging the files
System.out.println("Merging "+args[i]+" ...");
doc.loadUrl(args[i]);
doc.exportTo(ctx);
}
System.out.println("Document rendered succesfuly...");
}
The important points of this program are the following:
• A merge context object is created. The output destination, as well as the output
format are set.
Please note that only PDF and POSTSCRIPT are valid output formats. More output
formats may be added in the future.
• Each input is loaded into new instances of XFDocument, and then "exported" into the
merge context.
• When the merge context is disposed, the renderer will perform closing tasks on the
output. For PDF output this is equivalent with writing the trailer.
Copyright© 2002-2006 ECRION Software. All Rights Reserved.
Page 8 of 10
Ecrion
}
catch (Exception e)
{
System.out.println("Exception occured: "+ e);
}
finally
{
doc.dispose();//The document must be disposed properly
ctx.dispose();//The context must be disposed properly
}
}
Chapter 4: XF Rendering Server 2007 Java Tutorial
Remarks
The example above describes a generic way to merge multiple inputs into one output. You
can also use a OutputStream derivative object as parameter to SetOutput method.
Please note that the merge context must be closed gracefully in order to obtain a valid
output file.
Print
XF can print documents previously loaded with load or loadUrl method.
The following code fragment exemplifies this feature:
import com.ecrion.xf.*;
public class Print
{
static boolean validateCommandLine(String[] args)
{
if (args.length != 4 && args.length != 5)
return false;
if ((!args[0].equals("-fo")) || (!args[2].equals("-device")))
return false;
if (args.length == 5 && (!args[4].equals("-gdi")) && (!args[4].equals("-ps")) &&
(!args[4].equals("-pcl")))
return false;
return true;
}
public static void main(String[] args)
{
if (!validateCommandLine(args))
{
System.out.println("Prints a XSL-FO file to a printer.\n");
System.out.println("java -cp [set classpath] print -fo foFile -device printer
[-gdi | -ps]\n");
System.out.println(" -fo\t\tThe XSL-FO file to be printed.");
System.out.println(" -device\tThe printer name.");
System.out.println(" -gdi\t\tPrint using Widows GDI (default).");
System.out.println(" -ps\t\tPrint as POSTSCRIPT directly to the device.\n");
System.out.println("Examples:");
System.out.println(" For a local printer:java -cp [set classpath] \t print -fo
\"C:\\Test Print\\Test.fo\" -device HP4650");
System.out.println(" For a network printer:java -cp[set classpath] \t print -fo
\"C:\\Test Print\\Test.fo\" -device \\\\PRINTSRV\\HP4650");
System.out.println();
return;
}
fileName = args[1];//The full path to the file
printerName = args[3];
mode = args.length == 5 ? args[4]: "-gdi";
XFDocument doc = new XFDocument();
try
{
doc.loadUrl(fileName);
int
pageCount = doc.getPageCount();
System.out.println("Printing "+fileName+" to "+printerName+" using " +mode+"
mode...");
if (mode == "-gdi")
doc.printTo(printerName, XFDocument.XPF_GDI);
else if (mode == "-ps")
doc.printTo(printerName, XFDocument.XPF_PCL);
Copyright© 2002-2006 ECRION Software. All Rights Reserved.
Page 9 of 10
Ecrion
String
String
String
Chapter 4: XF Rendering Server 2007 Java Tutorial
else if (mode == "-pcl")
doc.printTo(printerName, XFDocument.XPF_POSTSCRIPT);
else
throw new Exception("Unrecognized option: "+mode);
doc.dispose();
}
catch (Exception e)
{
System.out.println("Exception occured: "+ e);
}
finally
{
doc.dispose();// XFDocuments must aways be disposed properly!
}
}
}
The important points of this program are the following:
• You must pass the command line arguments as the program explains.
• An instance of XFDocument is created and the document loads the input file given as
parameter.
• The printTo method is called and does the job for you. You must give the printer name
and the print mode. You can get the printer from Control Panel/Printers and Faxes
select a printer and right click properties.
Ecrion
Copyright© 2002-2006 ECRION Software. All Rights Reserved.
Page 10 of 10