Adding text to PDF after JFreeChrart – iText
March 29, 2010
kirankumar
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.
That’s explained in the book.
Your document.add() will work with a PdfTemplate if you wrap the PdfTemplate inside an Image object.
If you have a PdfTemplate named chart, you can do:
Image img = Image.getInstance(chart);
document.add(img);
document.add(new Paragraph(“Some text under a chart”));
Dear Bruno Lowagie,
A billion thanks for your response.
It is awesome. It is perfectly working.
Thank you once again for your iText source and the book.
Regards,
Kiran Kumar
My cousin recommended this blog and she was totally right keep up the fantastic work!
Hehe I’m honestly the only reply to this amazing read?!