Tuesday, December 21, 2004

PDF template creation using iText

This will sound exiting to those who know that , one can use the Adobe Arcobat writer toll to create templates. These templates can use used to fill up data programatically using iText api.

How would you do so ?.

Lets assume that you already have the itext.jar in class path and let's say you have create a template using adobe acrobat.

Then you call that template in your code like this :-

File template = new File(templatePDFFile);
byte[] templateByteArray = getBytesFromFile(template); // somehow get the bytes out of the file.
Document document - new Document();
FileOutputStream fos = new FileOutputStream(outputFileName);
PdfWriter writer = PdfWriter.getInstance(document, fos);
document.open();
PdfContentByte cb = writer.getDirectContent();

PDFReader = new PdfReader(templateByteArray);
HashMap fieldBoxes = getFieldBoxes(reader);// get all the fields of the template and then use them via stamper.
// now we use the stamper to do the template majic
stamp = new PdfStamper(reader, outputStream);
cbStamper = stamp.getOverContent(1);
form = stamp.getAcroFields();

rect = (Rectangle) fieldBoxes.get("mytestimage");
addSpecialImage(
cbStamper,
testImage,
rect.left(),
rect.bottom(),
rect.right(),
rect.top()
);

Here is what the addspecial image method in our code does

private void addSpecialImage(
PdfContentByte cb,
Image img,
float x1,
float y1,
float x2,
float y2)
{
float h = y2 - y1;
float w = x2 - x1;

try{
img.scaleToFit(x2 - x1, y2 - y1);
img.setAbsolutePosition(x1, y1);
cb.addImage(img);
}
catch (Exception e)
{
log(e.getMessage());
timeLog(e.getMessage());
e.printStackTrace();

}
}

However now you can create the template we used above also programatically on the fly using iText.

Here is some random code that does this:-

// llx - lower left x
// lly - lower left y
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(somepdfname));

document.open();
BaseFont helv = BaseFont.createFont("Helvetica", "winansi", false);
PdfContentByte cb = writer.getDirectContent();
cb.moveTo(0, 0);
float fontSize = DEFAULT_FONT_SIZE;
Color textColor = new GrayColor(0f);
PdfFormField field = PdfFormField.createTextField(writer, false, false, 0);
field.setWidget(new Rectangle(llx, lly, llx + DEFAULT_UPPER_X_DIFFERENCE, lly + DEFAULT_UPPER_Y_DIFFERENCE), PdfAnnotation.HIGHLIGHT_INVERT);
field.setFlags(PdfAnnotation.FLAGS_PRINT);
field.setFieldName(DEFAULT_FIELDNAME_STARTSTRING + j + "_" + i);
field.setBorderStyle(new PdfBorderDictionary(2, PdfBorderDictionary.STYLE_SOLID));
field.setPage();
PdfAppearance tp = cb.createAppearance(170, 30);
PdfAppearance da = (PdfAppearance)tp.getDuplicate();
da.setFontAndSize(helv, fontSize);
da.setColorFill(textColor);
field.setDefaultAppearanceString(da);
writer.addAnnotation(field);
document.close();

So this is the power of iText, it does so many nice things with PDF, some of them are undocumented.

0 Comments:

Post a Comment

<< Home