PDF form population with iText

August 6, 2010

iText is a powerful library that allows user to create and manipulate PDF files. Currently there are Java and .NET version of the library which proves to be one of the most popular tools for PDFs. Often used as part of web applications for generation of output for forms and document generation automation iText is free for use under the AGPL open source license. Keep in mind that this is not an end user utility but rather a developer tool for integration in applications and APIs.

In this example I will present the reader with a simple way of using iText for form fill automation. A simple example of how this comes useful is when a user fills information in a web form or a series of forms (as part of a workflow) and at the end is presented with an option to save or print a summary or an agreement. In this situation it is very useful to present the user with an opportunity to use Adobe’s PDF format in addition to plain HTML.

In order to proceed with the execution you will need the latest iText jar which you can find here. In addition you will have to have or create a PDF form which will be used in the automated form completion process. For the purposes of this example I have created a very simple form using Adobe Acrobat Professional which has just 2 simple fields: first name and last name. You can download the form used in this example Form. The two form fields are called FirstName and LastName. Next we can use the following java code to load the template, extract the form, and fill the desired information in the fields:

// get the destination
String location = "C:/java/pdf/src/";
if (location != null && !location.endsWith(File.separator))
{
location = location + File.separator;
}

PdfReader reader = new PdfReader(location + "Form.pdf");
String name = "Output.pdf";
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(location + name));
AcroFields form = stamp.getAcroFields();

String last = "subform[0].LastName[0]";
String first = "subform[0].FirstName[0]";

form.setField(last, "HRISTOV");
form.setField(first, "NEDKO");

// close pdf stamper
stamp.setFormFlattening(true);
stamp.close();
reader.close();

The snippet above creates a file called Output.pdf and fills the text values in. In addition to simple textboxes you can have checkboxes,  number fields, dropdowns, fields with format validation like phone numbers, social security numbers, barcodes etc. In the next example I provide a more complex form with different types of fields.

  • Share/Bookmark
0

10 Ways To Go Green

April 25, 2010

To celebrate Earth Day and after discovering that in recent research green index ranking (EPI – Environmental Performance Index) the U.S. ranks only 61 I decided to give some easy ideas how everybody can contribute to saving the environment in 10 easy ways. Contrary to common belief almost all the suggestions are about changing habits and behaviour rather than spending money. In fact if you follow the advice you will end up saving money.

1. Reduce your energy consumption – you can be very creative here: start by purchasing Energy Star products, not leaving lights and appliances working while not using them, be smart setting the thermostat of your heater and air conditioning to a reasonable level, use energy efficient light bulbs, don’t leave appliances on standby (this alone can reduce consumption by 10%), look at your bill for other suggestions. Efficiency programs are often available with your utility provider.

2. Reduce water use – don’t waste water. Starting from gardening, shower time, the kitchen you can be very creative. Use shower heads and facets that save water, monitor leaks, check your toilet water consumption.

3. Reduce gas consumption – use fuel efficient vehicle, telecommute, use public transportation, bike, walk, or use rideshare with a friend or coworker.

4. Eat smart – don’t waste food. Watch your food consumption and make sure you don’t waste any of it. Remember that one third of the people on earth are underfed. NEVER throw away good food. If your food goes bad change your shopping habits. Purchase locally raised products.

5. Buy smart – support products that use less packaging and employ environmentally friendly methods and by-products in their packaging.

6. Recycle – start by reading your news online and cancel that paper subscription. Separate your mail and trash and dispose of it properly. Cancel all your paper bills and sign up for online statements – that saves you and the company time and money and protects the environment.

7. Stop buying bottled water – I know the water from your sink just does not taste exactly the same but when filtered it’s equally healthy for you and does not produce all that thrash.

8. Dispose of unwanted items properly – old tvs, cellphones and other electronics come to mind. There are programs of proper disposal, recycling, and even reuse. One example if old cell phones for military personnel. Even if it means holding on to an item an extra week or two put your best effort in trying to pass it to somebody who will use it. Donate your old clothes that you don’t use to charity.

9. Share – before you buy this new book try the local library first. Share it with a friend. Resell it or donate it once you are done.

10. Try to influence the people around you to do the same – Remember word of mouth is the best marketing. Try to suggest new ways of doing things to the people around you without being too pushy. Respect their ways.

That’s my list of suggestions. I hope this helps and if you have any other ideas feel free to share them.

  • Share/Bookmark
0

Web application testing with JMeter

April 12, 2010

testing

It is hard to overstate the importance of testing before going live with a website or a web application. The rule of thumb is that whatever can go wrong will at exactly the most crucial moment. The problem is that your staging environment is inadequate and fails to replicate real scenarios. That’s where JMeter comes useful.

The open source load testing tool is written Java and allows testing functional behavior and performance under variable loads. Originally developed for testing Web Application JMeter has expanded and works with different servers and protocols: HTTP, HTTPS, SOAP, Database via JDBC, LDAP, JMS, mail through POP and IMAP. The tool is highly customizable and includes pluggable architecture as well as numerous built-in features like randomizers, timers, logic controllers, regular expression handling etc. The data collection,  analysis and visualization tools make it easy to get results fast come to valuable conclusions of the overall quality of your product. The tool comes as a desktop application with a clean, easy to use GUI. While it is not a browser (certain aspects as rendering, JavaScript execution are not covered)  it behaves as such as far as the remote client is concerned. It handles cookie and session management in full multithreading which allows concurrent sampling.

jmeter results graph

The user can write a test script or record one through the use of the built-in HTTP proxy server and then modify the parameters of the communication with the server (HTTP headers, request type and request parameters). To get started just download JMeter and read the JMeter Tutorial as well as the official documentation.

  • Share/Bookmark
0

Log4J Exceptions – Stack Trace Output and Handling

March 8, 2010

Overview

During my professional career I have become accustomed to the development tools that make the engineer’s job much easier. On the other hand I’ve come to the realization that little time and attention is being spent on optimization and proper use of those tools. While there is plenty of information out there on framework comparisons, guides, APIs, and the like very few products seem to adopt the best practices and the tier two functionality slips through the cracks of the Q&A process. This is usually the case with logging.
Log4J is the status quo when it comes to logging in Java. With the expanded mainstream popularity the framework which has been branched in C++ (Log4cxx) ,  C#/.NET (Log4Net) and even PHP (Log4php) has made it easy to add logging to multi tier applications. The advantage of having a very granular approach with different log levels (DEBUG, INFO, ERROR, etc.) and the Logger package inheritance make it a flexible tool. Without getting into details on the configuration and how to get started I want to spend time on the proper Logger initialization and use for exception handling.

Log4J Logger

As described in the Logger API we can get our Logger initialized inside the class in one of several ways the most common of which are:

- using the Class object

Logger log = Logger.getLogger(getClass());

- using a string

Logger log = Logger.getLogger(getClass().getName());

or

Logger log = Logger.getLogger("com.java.foo.MyClass");

Once we have a logger instance we can easily log messages with different threshold:

Foo foo = new Foo();
log.info("Created object foo: " + foo.toString());

or

if(log.isDebugEnabled())
{
	//do something
	log.debug("Result: " + foo.getResult());
}

Exception handling

It gets more interesting when we get to exception handling. In the regular try catch scenario we usually deal with some exception where we want to collect some output about what happened and where. A lot of times developers are tempted to use exception.getMessage() which is often empty or yet worse call exception.printStackTrace() which actually prints to the standard output rather than our log file. In order to successfully print the exception message and the stack trace we can add the exception to the logger output by doing this instead:

try
{
	computeInterestRates();
}
catch(Exception e)
{
	//something went wrong - log an error
	log.error("Error during RateCalc: ", e);
}

Conclusion

It is easy to get lost in requirements and miss on some of the essential product functionality. The proper use of logging helps reduce and eliminate defects in the lifecycle of the software and be a life saver in the long run. Make sure that you properly handle all logging. Keep in mind that the overuse of logging has a detrimental effect on performance so use it sparingly. For more information see the Log4j Official Documentation.

  • Share/Bookmark
0

J2EE classloading – java.lang.LinkageError

August 12, 2009

Recently while working on a java enterprise application I came upon a runtime error which later inspired this very post. What will follow will also give you a taste of what proper Maven dependency management should look like. The problem in question was a library call which caused the following to be spit in my error logs:

Caused by: java.lang.LinkageError: loader constraints violated when linking javax/activation/DataHandler class (more…)

  • Share/Bookmark
0

Face Detection Technology

August 4, 2008

Research has shown that 70% of the pictures we take feature people. Face detection in software in digital processors can greatly enhance the quality of images and help describe the content. Why not? While humans can easily identify objects in a photograph it takes a lot more to teach a machine how to do that and most of all …do it well. (more…)

  • Share/Bookmark
1

iGoogle Review

May 12, 2008

Along with the catchy name iGoogle has succeeded to put ‘personalized’ in search. While the idea is nothing new and has been present for long in competitor sites (My Yahoo! and Microsoft Life are a two examples which need no introduction) Google has been able to put a different spin on the concept. (more…)

  • Share/Bookmark
0

Blue Ray Vs. HD DVD – What did Sony learn from Betamax Vs. VHS

February 28, 2008

At the time I am writing this the battle is over and the dust is starting to settle as Toshiba just waived the white flag and announced that they are going to discontinue their HD DVD campaign and stop manufacturing HD DVD products. And most likely as you are reading this HD DVD will just be a piece of history …important history which goes long before I was even born – these are the days of the magnetic media revolution; the days when VHS players could reach ridiculous prices and could cost – up to half the price of a luxury vehicle. (more…)

  • Share/Bookmark
0

Google Apps Review – Should you switch?

December 21, 2007

should you switch to google appsGoogle Apps is a service providing customized solution for your company using several of Google’s products. By using Google Apps for your domain you can take advantage of Google’s mail service (Gmail) as well as several web applications including Google Calendar, Google Docs, Google Talk. Since Gmail now supports both POP and IMAP functionality it’s worth considering switching your in-house email solution to Google Apps and offload the need for hardware, software, administration and maintenance, backups etc. For those of you who are already thinking about it – keep reading. (more…)

  • Share/Bookmark
2

Multipart MIME email example in PHP

November 23, 2007

Let’s see how we can use some simple tools and create a functional example of how multipart MIME actually works in practice. With both of my hands in the carburetor (a car repair term for getting down to business and having things done fast) I sit down and get busy with creating the necessary form and php script. Before I get into more details I want to make clear that you will need PHP set up correctly. For the purposes of creating something interactive we’ll use our code in the context of an Apache 2 web server which will make testing and using the application easier. (more…)

  • Share/Bookmark
4