【问题标题】:iText PdfContentByte addTemplate position does not effectiText PdfContentByte addTemplate 位置不影响
【发布时间】:2010-12-28 01:29:26
【问题描述】:

我正在尝试将位置设置为我添加到 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(); 

【问题讨论】:

    标签: image pdf positioning itext


    【解决方案1】:

    您的模板是空的...您直接从作者的直接内容中获取 PdfGraphics2D(CB.createGraphics 而不是您可能想要的,TP.createGraphics)。

    有几种解决方案:

    选项 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(...);
    

    【讨论】:

    • 非常感谢,非常感谢。我应该越来越多地处理 itext。
    猜你喜欢
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多