Using iText with jFreecharts inside a Pdftable


If you've used the iText library and tried to add a jfreechart in the Pdf, inside a table cell, you'd soon run into atleast one of the following problems:

1. The image either does not appear at all!
2. The image gets resized automatically to the size of the cell.
3. the quality of the image is terrible!. Get a print and its unacceptable for any professional work

So here are some solutions:

1. Any type of content in iText PdfPTable only appears if all the cells have values. Skip adding one PdfPCell and the PdfPRow will not be rendered!. Does not seem to be documented anywhere but hope it helps the struggling.

2. There are two ways to add the image:

a. The straight way (Image will be resized)

PdfPTable table = new PdfPTable (1);
Image image = Image.getInstance("http://yoururl.com");
table.addCell(image);

b. The Cell way (Image does not resize)

PdfPTable table = new PdfPTable (1);
Image image = Image.getInstance("http://yoururl.com");
PdfPCell cellImage = new PdfPCell();
cellImage.addElement(image);
table.addCell(cellImage);


3. The basic quality of the image exported with ChartUtilities.saveAsPng is terrible for print graphics, but The developers of iText also provide the com.itext.graphics2d package which allows one to draw directly on the pdf using PdfPTemplate... Some source code below:

int width = 200;
int height = 200;
Document document = new Document(PageSize.A4);
PdfWriter = new PdfWriter(document);
PdfContentByte cb = new PdfContentByte(writer);
            

PdfPTable tableGraphs = new PdfPTable(1);

PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height);
Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
graph.draw(g2, r2D);
g2.dispose();
           
Image graphImage = Image.getInstance(tp);
graphImage.scaleToFit(width, height);
           
PdfPCell cell = new PdfPCell();
cell.addElement(graphImage);
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);


tableGraphs.addCell(cell);


All the best!





Comments

Popular Posts