开发者

chart location of pie chart in iText pdf in java

I'm creating a pie chart using jFreechart and add the chart in pdf created in iText. The problem is chart is always added at the bottom of the page and not after the last line.

A sample code for regenrating the error is:

Document document = new Document();
PdfWriter writer;
File file = new File("c:/myPdf.pdf");
writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();

try {
        DefaultPieDataset pieDataset = new DefaultPieDataset();
        pieDataset.setValue("OPT 1", 10);
        pieDataset.setValue("OPT 2", 0);
        pieDataset.setValue("OPT 3", 17);
        pieDataset.setValue("OPT 4", 11)开发者_如何学Python;
        JFreeChart chart = ChartFactory.createPieChart3D("Option click count", 
                pieDataset, true, false, false);

        final PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setNoDataMessage("No data to display");
        chart.setTitle(new TextTitle("Option Click Count", new Font("Times New Roman", Font.PLAIN, 14)));

        PdfContentByte pdfContentByte = writer.getDirectContent();
        PdfTemplate pdfTemplateChartHolder = pdfContentByte.createTemplate(225,225);
        Graphics2D graphicsChart = pdfTemplateChartHolder.createGraphics(225,225,new DefaultFontMapper());
        Rectangle2D chartRegion =new Rectangle2D.Double(0,0,225,225);
        chart.draw(graphicsChart,chartRegion);
        graphicsChart.dispose();
        pdfContentByte.addTemplate(pdfTemplateChartHolder,0,0);
    } catch (Exception e) {
        e.printStackTrace();
    } 
document.close();

Here the options are fetched from database so not sure on the count of the option. I want to show chart right to the table. How can I do this?


You are adding the chart as a template, and per definition they are added with absolute coordinates.

If you are using floating elements, as I assume you are, you can use com.lowagie.itext.Image (version 2.1), and in newer versions com.itextpdf.text.Image.

You can use the Image class to create the template, and add it as a Element:

See here (iText API).

PdfContentByte pdfContentByte = writer.getDirectContent();
PdfTemplate pdfTemplateChartHolder = pdfContentByte.createTemplate(225,225);
Graphics2D graphicsChart = pdfTemplateChartHolder.createGraphics(225,225,new DefaultFontMapper());
Rectangle2D chartRegion = new Rectangle2D.Double(0,0,225,225);
chart.draw(graphicsChart,chartRegion);
graphicsChart.dispose();

Image chartImage = Image.getInstance(pdfTemplateChartHolder);
document.add(chartImage);

The code example above shows the gist of it. You should as often as possible use Element objects such as Image if you don't want to handle heights and positions absolutely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜