将 BufferedImage 添加到 PDFBox 文档
在我当前的项目中,我尝试将 BufferedImage
添加到 PDFBox 文档中。更具体地说,我使用来自 JFreeChart
的图像。我的代码如下所示:
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();
}
文档被创建;我可以添加文本,但收到一条错误消息,指出图像没有足够的信息可显示。
有什么线索表明我做错了什么吗?
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.
Any clue to what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
谢谢你帮我摆脱垃圾之神。昨晚和今天花了几个小时对 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.
I´m sure this can be done better but it works.
有一种简单的方法可以使用 pdfbox 将 JFreeChart 插入 pdf:
没有任何流;)
There is an easy way to insert a JFreeChart into a pdf with pdfbox:
Without any stream ;)
有两点值得注意:
不要吞下异常。
请使用
ChartUtilities
以合适的格式呈现图像,如建议的此处。Two things stand out:
Do not swallow exceptions.
Do use
ChartUtilities
to render the image in a suitable format, as suggested here.