Daily Archives: March 29, 2010

Adding text to PDF after JFreeChrart – iText

I heard about a problem of adding text to the PDF after the JFreeChart, using iText.  It’s really a puzzled question?

Generally we will use the method “document.add(txtElement)” to add the text into PDF. It is clear that we are adding the text as an element. Suppose if you add five elements to the PDF, it will add them in the order from the top. But here you have not added the JFreeChart as an Element. It’s a Pdf Template adding to the PDF document as a Pdf content. iText will render the Pdf Content from the bottom left corner. You have to position it in the document to the exact place you want. So, your “document.add(txtElement)” wont work here.

Hence, You have to add the text too as a PdfContent. Here is the code to solve the problem,

PdfContentByte txtContent = writer.getDirectContent();
txtContent.beginText();

BaseFont font = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

String text = "This is the text I am going to add to the pdf at the bottom of the JFreeChart".

int xPos = 10;    //To Changed according to your need
int yPos = 100;  // To Changed according to your need

txtContent.setFontAndSize(font,10);

txtContent.showTextAligned(0, text, xPos, yPos, 0f);

txtContent.endText();

I hope the above code will solve your problem.