I'm trying to output a JUNG network to a PDF using the iText library.
Many solutions seem to display the graph in a frame before using a library to capture the screen and output this to some format such as EPS. However, my application will automatically build many networks and output them so displaying each network on the screen before saving to a file is not a great solution.
I've done some searching and not come across exactly what I'm doing. It seems straightforward to output the graph to a PNG (see here) but the quality of a PNG is not suitable for my needs.
My current code is below and is based on writing charts from JFreeChart to PDF (see here). I'm trying to get a Graphics2D object that I can "draw" the graph onto and then output to PDF. This code generates a null pointer exception as the graphics object returned from visualise.getGraphics() is null.
Any advice, code snippets or online examples would be appreciated.
public void write() throws IOException, DocumentException {
// Open the PDF file for writing
this.document = new Document();
this.writer = PdfWriter.getInstance(this.document, new FileOutputStream(this.fileName));
document.open();
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate template = contentByte.createTemplate(WIDTH, HEIGHT);
//Graphics2D graphics2d = template.createGraphics(WIDTH, HEIGHT, new DefaultFontMapper());
// Apply a layout to the graph
Layout<Vertex, Edge> layout = new CircleLayout<Vertex, Edge>(this.network);
layout.setSize(new Dimension(WIDTH, HEIGHT));
// Draw on the graphics 2D object
VisualizationImageServer<Vertex, Edge> visualise = new VisualizationImageServer<Vertex, Edge>(layout, new Dimension(WIDTH, HEIGHT));
visualise.setPreferredSize(new Dimension(WIDTH + 50, HEIGHT + 50));
visualise.setDoubleBuffered(false);
Graphics2D graphics2d = (Graphics2D) visualise.getGraphics();
visualise.paintComponents(graphics2d);
graphics2d.dispose();
contentByte.addTemplate(template, 0, 0);
this.document.close();
}