如何将图表插入pdf

如何将图表插入pdf

本文介绍了如何将图表插入pdf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制两个图表,显示带有标签的堆积条形图,用Java编写PDF文件。我会从Mongodb获取数据以输入图形。该怎么做?

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?

推荐答案

使用JFreechart和pdfbox我做了类似于你要求我做一次报告的内容。制作饼图如下:

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.");
        }
    }
}

上面的例子来自于pdf我认为可以在他们的网站上找到,如果你需要,它有其他图表的例子。保存后,我可以将其导入pdf,类似于:

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也是一个很好的pdf操作库,但是点而pdfbox应该是开源的。

itext is also a good library for pdf manipulation, but that is commercial after a point whereas pdfbox should be open source.

祝你好运!

这篇关于如何将图表插入pdf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 07:42