article

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

Email
Submitted on: 1/2/2015 12:22:00 PM
By: Manjunath P Reddy (from psc cd)  
Level: Intermediate
User Rating: By 9 Users
Compatibility: Java (JDK 1.1), Java (JDK 1.2)
Views: 4010
 
     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
 
				

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


Other 3 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


 There are no comments on this submission.
 

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.