iText PdfContentByte addTemplate位置不起作用

时间:2010-12-27 15:24:52

标签: image pdf positioning itext

我正在尝试将位置设置为我添加到PDF的图像,但它始终位于0,0。 我搜索了很多,但找不到解决方案。我想我不能很好地理解定位。

以下代码总是位于0,0但应该是200,300!

非常感谢你的帮助,

DefaultPieDataset dataset = new DefaultPieDataset();

dataset.setValue(String.format("%s, %s", "pie1", "pie1"),20);
dataset.setValue(String.format("%s, %s", "pie2", "pie2"),80);

JFreeChart chart = ChartFactory.createPieChart("testPie", dataset, true, true, false);

Document document = new Document();
document.addCreationDate();
document.setPageSize(PageSize.A4);

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("test.pdf")); 
document.open(); 

PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(300, 300); 
Graphics2D g2 = cb.createGraphics(300, 300, new DefaultFontMapper()); 

Rectangle2D r2D = new Rectangle2D.Double(0, 0, 300, 300); 
chart.draw(g2, r2D, null); 
g2.dispose(); 
cb.addTemplate(tp, 200, 300); 
document.close(); 

1 个答案:

答案 0 :(得分:0)

你的模板是空的......你直接从作者的直接内容(CB.createGraphics而不是你想要的,TP.createGraphics)获得PdfGraphics2D。

有几种解决方案:

选项1:从模板中获取Graphics2D

 Graphics2D g2 = tp.createGraphics(...)

选项2:抛弃模板,直接在contentByte中移动图表。 graphics2D界面有点笨重,所以你应该尽可能直接在contentByte中做事。它工作正常,但它构建的内容流不如它有效。在这种特殊情况下,我认为这不重要,但这是一个很好的经验法则。

 cb.saveState();
 cb.concatMatrix(1, 0, 0, 1, 200, 300);
 Graphics2D g2 = cb.createGraphics(...);
 ...
 g2.dispose();
 cb.restoreState();
 document.close();

选项三:抛弃模板并从Graphics2D实例中移动图表:

 g2.transform(AffineTransform.getTranslateInstance(200, 300));
 chart.draw(...);