使用 PDFBox 将字节 [] 打印为 PDF [英] Print byte[] to PDF using PDFBox

查看:61
本文介绍了使用 PDFBox 将字节 [] 打印为 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用 PDFBox 将图像写入 PDF 的问题.

I have a question about writing image to PDF using PDFBox.

我的要求很简单:我使用 Spring RestTemplate 从 Web 服务获取图像,将其存储在 byte[] 变量中,但我需要绘制将图像转换为 PDF 文档.

My requirement is very simple: I get an image from a web service using Spring RestTemplate, I store it in a byte[] variable, but I need to draw the image into a PDF document.

我知道提供了以下内容:

I know that the following is provided:

final byte[] image = this.restTemplate.getForObject(
        this.imagesUrl + cableReference + this.format,
        byte[].class
);

JPEGFactory.createFromStream() 用于 JPEG 格式,CCITTFactory.createFromFile() 用于 TIFF 图像,LosslessFactory.createFromImage() 如果以缓冲图像.但我不知道该用什么,因为我所知道的关于这些图像的唯一信息是它们是 THUMBNAIL 格式,我不知道如何从 byte[] 转换为这些格式.

JPEGFactory.createFromStream() for JPEG format, CCITTFactory.createFromFile() for TIFF images, LosslessFactory.createFromImage() if starting with buffered images. But I don't know what to use, as the only information I know about those images is that they are in THUMBNAIL format and I don't know how to convert from byte[] to those formats.

非常感谢您的帮助.

推荐答案

(适用于 2.0 版,不适用于 1.8 版)

(This applies to version 2.0, not to 1.8)

我不知道你对 THUMBNAIL 格式的意思,但试试这个:

I don't know what you mean with THUMBNAIL format, but give this a try:

    final byte[] image = ... // your code
    ByteArrayInputStream bais = new ByteArrayInputStream(image);
    BufferedImage bim = ImageIO.read(bais);
    PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bim);

也许可以通过使用来创建更高级的解决方案

It might be possible to create a more advanced solution by using

PDImageXObject.createFromFileByContent()

但是这个使用文件而不是流,所以它会更慢(但会产生最好的图像类型).

but this one uses a file and not a stream, so it would be slower (but produce the best possible image type).

要将此图像添加到您的 PDF,请使用以下代码:

To add this image to your PDF, use this code:

    PDDocument doc = new PDDocument();
    try
    {
        PDPage page = new PDPage();
        doc.addPage(page);

        PDPageContentStream contents = new PDPageContentStream(doc, page);

        // draw the image at full size at (x=20, y=20)
        contents.drawImage(pdImage, 20, 20);

        // to draw the image at half size at (x=20, y=20) use
        // contents.drawImage(pdImage, 20, 20, pdImage.getWidth() / 2, pdImage.getHeight() / 2);

        contents.close();
        doc.save(pdfPath);
    }
    finally
    {
        doc.close();
    }

这篇关于使用 PDFBox 将字节 [] 打印为 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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