Important alert: (current site time 7/15/2013 2:26:09 PM EDT)
 

article

Quick n' easy way of generating pdf's on the fly using FOP and Java.

Email
Submitted on: 5/17/2001 2:49:41 PM
By: Manjunath P Reddy 
Level: Intermediate
User Rating: By 9 Users
Compatibility: Java (JDK 1.1), Java (JDK 1.2)
Views: 39685
 
     This article illustrates a very easy way of getting started with the print formatting objects using FOP. By the end of the article you should be able to generate pdf's on the fly using an xml and xsl document.

This article has accompanying files
 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				

Quick n' easy way of generating pdf's on the fly using FOP and Java.

This article illustrates a very easy way of getting started with the print formatting objects using FOP. For more details on FOP check out the xml.apache.org. All due credit goes to the guys who worked on the world's first FOP. These generic objects give an easy access to generating professional pdf's on the fly from xml documents using fop,xalan and xerces for DOM.

I used them for generating runtime agreements in pdf depending on the user selected channels,period,categories etc..for a licensing engine.

The example works on any environment with jdk1.2/1.3 installed. My contribution is a simple wrapper for the fop packages(org.apache.fop.apps.XMLFormatter) so that one can directly make use of the whole model by calling the methods XMLFormatter.formatToPDF() or XMLFormatter.formatToText().

Before starting lets see what FOP is all about. I reproduce below a snippet from the fop readme which says...

----------------------
 What is FOP?
 FOP is the world's first print formatter driven by XSL formatting
 objects. It is a Java application that reads a formatting object
 tree conforming to the XSL candidate release (21. November 2000) and
 then turns it into a PDF document or allows you to preview it
 directly on screen.
 FOP is part of Apache's XML project. The homepage of FOP is
 http:/xml.apache.org/fop
 HTML-Documentation can be found in the subdirectory docs/html-docs.
 A list of bugs, things worked on, and the names of the committers of
 this project can be found in the file status in root.
----------------------

How do i start? Make sure the unzipped xalan.jar,xerces.jar,w3c.jar and fop.jar are in your class path. Also copy the sample xml xsl files into ur application directory and then copy paste the source code below which is an example of accessing the helper class XMLFormatter(wrapper for the conversion of xml and given xsl to pdf/text). Make necessary changes for the file path of the xml,xsl and pdf/text in the example class given. Run the program...and the pdf/text would be generated at the path specified in the class.

Please use the sample xml,xsl and generated pdf's just as an example and not as standards for writing your own xml or xsl. Comprehensive document is available at xml.apache.org for the various formatting tags that can be used for building better pdf's.

Here's the sample source code for invoking the wrapper...

/**
 * Test Class to call the wrappers for FOP objects
 * to generate pdf/text files. The inputs for conversion
 * are xml file name and xsl file name as well as the 
 * text/pdf file name to be rendered to.
 * @Class FormatterTest
 * @Created by/on M.Reddy 17/May/2001
 */
import java.util.*;
import java.io.*;
import org.apache.fop.apps.XMLFormatter;
public class FormatterTest{
//static constants storing the file paths for the xml,xsl and the pdf
private static final String XML_PATH = "c:/fop";
private static final String XSL_PATH = "c:/fop";
private static final String PDF_PATH = "c:/fop";
private static final String TEXT_PATH = "c:/fop";
public FormatterTest()	{}	// End Default Constructor
	
	
	//for rendering the given xml and xsl file to pdf file
	private void renderToPDF(String xmlfilename,String xslfilename,String pdffilename)
	{
		//construct arguments here
		String xmlFilePath ="file:///" + FormatterTest.XML_PATH + 
		 	File.separatorChar + xmlfilename;
		
 	String xslFilePath ="file:///" + FormatterTest.XSL_PATH + 
							File.separatorChar + xslfilename;
		
 	String pdfFilePath =FormatterTest.PDF_PATH + 
 	 	File.separatorChar + pdffilename;
		
		//for now use paths from arguments passed later retrieve from an init servlet
		String args[] = new String[3];
		args[0]=xmlFilePath;
		args[1]=xslFilePath;
		args[2]=pdfFilePath;
		
		try
		{
			XMLFormatter.format2Pdf( args );
		}catch(Exception e)
		{
			System.out.println("Exception in rendering to Pdf " + e.toString() );
		}
	}
//for rendering the given xml and xsl file to text file
	private void renderToText( String xmlfilename, String xslfilename ,String textfilename)
	{
		String xmlFilePath ="file:///" + FormatterTest.XML_PATH + 
							File.separatorChar + xmlfilename;
		
		String xslFilePath ="file:///" + FormatterTest.XSL_PATH + 
							File.separatorChar + xslfilename;
							
 	String textFilePath =FormatterTest.TEXT_PATH + 
							File.separatorChar + textfilename;
		
		
		String args[] = new String[2];
		
		args[0]=xmlFilePath;
		args[1]=xslFilePath;
		
		
		String data="";
		
		try
		{
			data = XMLFormatter.format( args );
			
			try {
				 byte b[] = data.getBytes();
				 FileOutputStream outstream = new FileOutputStream(textFilePath);
				 outstream.write(b);
				 outstream.close();						 
			} catch(java.io.IOException e) {
			 System.out.println("Cannot write to " + textFilePath);
			}
			
		}catch(Exception e)
		{
			System.out.println("Exception in rendering to Text " + e.toString() );
		}
	}
//helper class wrapper methods
//Test suite
	public static void main(String[] args)
	{
		try
		{
			new FormatterTest().renderToPDF("sample.xml","pdf.xsl","sample.pdf");
			//System.out.println("Successfully generated pdf....");
			
			new FormatterTest().renderToText("sample.xml","text.xsl","sample.txt");
			//System.out.println("Successfully generated text....");
			
		}catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}

So guys..the above sample should work fine as long as the jars i mentioned are in your classpath. For making it easier on you i have included a batch file to get you started. Be sure you edit the format.bat and give the right path to ur unzipped folder. My suggestion is unzip the folder to root of c directory and then its as easy as it can get. You can manipulate the xsl or xml file and also visit the FOP site for more advanced information. Happy Programming!!!


-------------------------------------------------------
Please vote for me if u find the article/code useful...
thanks!

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come out every day, so no prevention program can catch 100% of them. For your own safety, please:
  1. Re-scan downloaded files using your personal virus checker before using it.
  2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

If you don't have a virus scanner, you can get one at many places on the net including:McAfee.com

 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.


Other 2 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments
9/11/2001 2:50:00 AMtheferry

this is a good article, but i found some problem when implemented....
where i can find xmlformatter.java ? because my fop.jar have no xmlformatter
thank's
(If this comment was disrespectful, please report it.)

 
9/12/2001 2:24:44 AMtheferry

finally i found that this article is really work. wonderful, thank's
(If this comment was disrespectful, please report it.)

 
7/10/2002 5:54:34 AMNaren

Hey even i had the same problem. I could not find the XMLFormatter wrapper class. Can you please mention where can i get the files.
(If this comment was disrespectful, please report it.)

 
7/16/2002 9:36:52 AMStephan

Hi,

I like your example very much! Because I'm working in the moment upon a site with need for that functionality I would like to ask you whether you have a JSP example ready for the above or at least can provide the classes used for the above. Thanks a lot.

Stephan
stephan.mayr@koeln.de
(If this comment was disrespectful, please report it.)

 
7/25/2002 2:07:41 PMubik

XMLFormatter.class it's in xalan.zip, under org/apache/fop/apps...I think most ides know to make the sum of the classes for 2 jars with the same path.
I wonder too why he didn't put it under fop.zip apps dir though.

Something else, dude, you should'v submit the XMLFormatter.java also.
(If this comment was disrespectful, please report it.)

 
12/9/2002 1:56:30 PM

Hi I am unable to find org.apache.fop.apps.XMLFormatter.
I'll appreciate if some one could send me either class of correct fop.jar file.

-thanx (abdul.qadir@oit.state.nj.us)
(If this comment was disrespectful, please report it.)

 
1/13/2005 7:26:20 AM

It's good article,can you please let me know how can i use the same for JSP/Servlet
(If this comment was disrespectful, please report it.)

 
1/13/2005 7:27:32 AM

Hi,
it's good article,can you please let me know that how can the same thing be done for JSP/Servelet
(If this comment was disrespectful, please report it.)

 
6/3/2005 3:05:12 PMdsummerfield

Hi, looks like a great article. However as a newbie I am struggling when trying to compile - would be great if you could kindly advise.

FormatterTest.java:11: package org.apache.fop.apps does not exist
import org.apache.fop.apps.XMLFormatter;
^
FormatterTest.java:49: cannot resolve symbol
symbol : variable XMLFormatter
location: class FormatterTest
XMLFormatter.format2Pdf( args );
^
FormatterTest.java:85: cannot resolve symbol
symbol : variable XMLFormatter
location: class FormatterTest
data = XMLFormatter.format( args
);
^
3 errors
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.