Search code examples
javaimageitextjfreechart

Postioning JFreeChart Image with Itext 5


I have created a JFreeChart image and am having trouble positioning it. The lower left corner of the image is placed on the lower left corner of the page.

Rectangle page=writer.getPageSize();
// swap X and Y for Landscape dimensions
float sizeX=page.getHeight();
float sizeY=page.getWidth();
float scale=.7f;
float marginY=10.f;
float marginX=50.f;
PdfContentByte cb=writer.getDirectContent();
PdfTemplate tp=cb.createTemplate(sizeX*scale+1,sizeY*scale+1);
PdfGraphics2D g2d=new PdfGraphics2D(tp,sizeX*scale+1,sizeY*scale+1);
tp.setWidth(sizeX*scale+1);
tp.setHeight(sizeY*scale+1);
Chart.getInstance().getChart().draw(g2d, new java.awt.geom.Rectangle2D.Float(0,0,sizeX*scale,sizeY*scale));
g2d.dispose();
Image image=Image.getInstance(tp);
image.setAbsolutePosition(marginX, sizeY-350.f);
document.add(image);

I would like the upper left corner of the image to be placed at the current cursor position. What am I doing wrong? TIA.


Solution

  • You create the PdfGraphics2D for the direct page content cb, not the template tp:

    PdfGraphics2D g2d=new PdfGraphics2D(cb,sizeX*scale+1,sizeY*scale+1);
    

    Thus, the chart is directly drawn into cb and your handling of tp does not matter at all!

    You should, therefore, initialize PdfGraphics2D with the template tp:

    PdfGraphics2D g2d=new PdfGraphics2D(tp,sizeX*scale+1,sizeY*scale+1);
    

    Furthermore you add tp to the page twice, first to its direct content

    cb.add(tp);
    

    and then wrapped in an Image instance to its Document document.

    Image image=Image.getInstance(tp);
    image.setAbsolutePosition(marginX, sizeY-marginY);
    document.add(image);
    

    Obviously you should add it but once.