I am trying to set position to image which i added to PDF but it always positions to 0,0.
I searched a lot but could not find the solution. I think i could not understand well about positioning.
Here is the code that always postions to 0,0 but it should be 200,300!
Thanks a lot for your help,
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue(String.format("%s, %s", "pie1", "pie1"),20);
dataset.setValue(String.format("%s, %s", "pie2", "pie2"),80);
JFreeChart chart = ChartFactory.createPieChart("testPie", dataset, true, true, false);
Document document = new Document();
document.addCreationDate();
document.setPageSize(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("test.pdf"));
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(300, 300);
Graphics2D g2 = cb.createGraphics(300, 300, new DefaultFontMapper());
Rectangle2D r2D = new Rectangle2D.Double(0, 0, 300, 300);
chart.draw(g2, r2D, null);
g2.dispose();
cb.addTemplate(tp, 200, 300);
document.close();
Your template is empty… you’re getting the PdfGraphics2D directly from the writer’s direct content (CB.createGraphics instead of what you probably intended, TP.createGraphics).
There are several solutions:
option 1: get the Graphics2D from the template
option 2: ditch the template, move the chart directly in the contentByte. The graphics2D interface is a bit clunky, so you should generally prefer to do things directly in the contentByte whenever possible. It works fine, but the content stream it builds isn’t as efficient as it could be. In this particular case, I don’t think it’ll matter, but that’s a good rule of thumb.
Option three: Ditch the template and move the chart from within the Graphics2D instance: