我正嘗試使用iText庫將JUNG網絡輸出爲PDF。使用iText將JUNG可視化輸出爲PDF
許多解決方案似乎都在使用庫來捕獲屏幕並將其輸出爲某種格式(如EPS)之前在框架中顯示圖形。但是,我的應用程序會自動構建許多網絡並輸出它們,因此在保存到文件之前在屏幕上顯示每個網絡並不是一個好的解決方案。
我已經完成了一些搜索,並沒有發現我正在做什麼。將圖表輸出到PNG似乎很簡單(請參閱here),但PNG的質量不適合我的需要。
我目前的代碼如下,並基於將圖表從JFreeChart寫入PDF(請參閱here)。我試圖得到一個Graphics2D對象,我可以「繪製」圖形並輸出爲PDF。此代碼生成空指針異常,因爲從visualise.getGraphics()返回的圖形對象爲空。
任何意見,代碼片段或在線示例將不勝感激。
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();
}