如何使用iText7在PdfDocument中呈现java.awt.Graphics2D?

时间:2017-05-24 12:22:20

标签: itext7

//writer is an instance of PdfWriter
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate temp = contentByte.createTemplate(width ,height);
Graphics2D g2d = temp.createGraphics(width, height);
Rectangle2D r2d = new Rectangle2D.Double(0,0,width ,height);
//chart is an instance of JFreeChart and info is the information required for rendering a chart in JFreeChart
chart.draw(g2d,r2d,info);
img = Image.getInstance(temp);
document.add(img);

这是iText 5中的代码。如何使用Itext7获取Graphics2D对象?

1 个答案:

答案 0 :(得分:1)

在更新版本时遇到同样的问题,这是我最终得到的解决方案:

document.add(convertChartToImage(chart));

其中convertChartToImage(...)如下:

private Image convertChartToImage(JFreeChart chart) throws IOException {
    Image result = null;
    BufferedImage original = chart.createBufferedImage(WIDTH, HEIGHT);
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {

        ImageIO.write(original, "png", os);
        os.flush();

        ImageData image = ImageDataFactory.create(os.toByteArray());

        result = new Image(image);
    }

    return result;
}

希望这会有所帮助。可能有更好的方法。