I would like to draw two graphs showing stacked bar graphs with labels, into a PDF file in Java. I would get the data from a Mongodb for input to graphs. How to do that?
4 Answers
Using JFreechart and pdfbox I have done something similar to what you are requesting for a report I made once. Making a pie chart was as follows:
public class PieChartExample {
    public static void main(String[] args) {
        // Create a simple pie chart
        DefaultPieDataset pieDataset = new DefaultPieDataset();
        pieDataset.setValue("Chrome", new Integer(42));
        pieDataset.setValue("Explorer", new Integer(24));
        pieDataset.setValue("Firefox", new Integer(24));
        pieDataset.setValue("Safari", new Integer(12));
        pieDataset.setValue("Opera", new Integer(8));
        JFreeChart chart = ChartFactory.createPieChart3D(
            "Browser Popularity", // Title
            pieDataset, // Dataset
            true, // Show legend
            true, // Use tooltips
            false // Configure chart to generate URLs?
        );
        try {
            ChartUtilities.saveChartAsJPEG(new File("C:\\Users\\myname\\Desktop\\chart.jpg"), chart, 500, 300);
        } catch (Exception e) {
            System.out.println("Problem occurred creating chart.");
        }
    }
}
The above example came from a pdf I think is available on their website, it has examples for other charts if you need them. Once saved, I could import it to the pdf similarly to this:
try {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page); 
    InputStream in = new FileInputStream(new File("c:/users/myname/desktop/chart.jpg"));            
    PDJpeg img = new PDJpeg(document, in);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.drawImage(img, 10, 300);
    contentStream.close();
    document.save("pathway/to/save.pdf");
} catch (IOException e) {
    System.out.println(e);
} catch (COSVisitorException cos) {
    System.out.println(cos);
}
itext is also a good library for pdf manipulation, but that is commercial after a point whereas pdfbox should be open source.
Good Luck!
 
    
    - 3,796
- 3
- 24
- 29
You can take a look at JasperReports. It's a Java framework for generating reports in PDF and other file formats. It has integrated support for various types of charts using the JFreeChart library.
However, I should warn you that the learning curve for JasperReports is quite steep. Perhaps you could consider using a combination of JFreeChart with iText instead, as suggested in this post.
you can use any charting library to generate the chart (somme libraries examples here), and then add it to your PDF using Itext.
 
    
    - 1
- 1
 
    
    - 4,287
- 1
- 32
- 41
 
     
     
    