将BufferedImage添加到PDFBox文档 [英] Add BufferedImage to PDFBox document

查看:186
本文介绍了将BufferedImage添加到PDFBox文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的项目中,我尝试将 BufferedImage 添加到PDFBox文档中。更具体地说,我使用 JFreeChart 中的图像。我的代码如下所示:

In my current project, I try to add a BufferedImage to a PDFBox document. More specificly, I use an image from a JFreeChart. My code looks like this:

public void exportToPDF(JFreeChart chart, String filePath){
    PDDocument doc = null;
    PDPage page = null;
    PDXObjectImage ximage = null;

    try {
        doc = new PDDocument();
        page = new PDPage();
        doc.addPage(page);
        PDPageContentStream content = new PDPageContentStream(doc, page);
        BufferedImage image = chart.createBufferedImage(300, 300);
        ximage = new PDJpeg(doc, image);
        content.drawImage(ximage, 20, 20);
        content.close();
    } catch(IOException ie) {
    }
    doc.save(filePath);
    doc.close();
}

文档已创建;我可以添加文字,但是我收到一条错误,说明图片没有足够的信息显示。

The document gets created; I can add text, but I get an error stating the the image does not have enough information to be shown.

我做错了什么线索?

推荐答案

感谢您帮我解决垃圾邮件问题。今晚花了几个小时和今天几个小时混淆了PipedIn / OutStreams。无法弄清楚。但是,我得到了它的工作。事实证明这并不困难。

Thanks for helping me out trashgod. Spent last night and a few hours today beeing confused about PipedIn/OutStreams. Can´t figure it out. However, i got it to work. Turns out it wasn´t very difficult at all.

public void exportToPDF(JFreeChart chart, String filePath){
    PDDocument doc = null;
    PDPage page = null;
    PDXObjectImage ximage = null;
    try {
        doc = new PDDocument();
        page = new PDPage();
        doc.addPage(page);
        PDPageContentStream content = new PDPageContentStream(doc, page);

        //create a new outStream
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ChartUtilities.writeChartAsJPEG(out, chart, 300, 300);//write to outstream
        //create a new inputstream
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        ximage = new PDJpeg(doc, in);
        content.drawImage(ximage, 5, 300);
        content.close();
    }
    catch (IOException ie){
        //handle exception
    }
    //save and close
    doc.save(filePath);
    doc.close();
}

我确信这可以做得更好但是有效。

I´m sure this can be done better but it works.

这篇关于将BufferedImage添加到PDFBox文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆