【问题标题】:How to convert Byte Array to image using itextPdf and display in pdf如何使用 itextPdf 将字节数组转换为图像并以 pdf 格式显示
【发布时间】:2016-11-16 10:18:49
【问题描述】:

如何将字节数组转换为itext pdf中的图像并以pdf格式显示。 这就是我正在做的,但我得到空指针异常..

    Base64 decoder = new Base64();
    byte[] imageByte = decoder.decode(imageInBase64EncodedString);
        Image image = null;
        try {
            image = Image.getInstance(imageByte);
        } catch (BadElementException e1) {
            e1.printStackTrace();
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            image.scalePercent(15f);  <-----Here i am getting NullPointer Exception
            image.scaleAbsoluteWidth(520f);
            image.setAbsolutePosition(40f,725f);
            document.add(image);
       }catch(Exception e){
            e.printStackTrace();
       }

我不明白为什么即使我传递了字节也没有创建图像。

【问题讨论】:

  • 上面的printStackTrace调用是否触发了?
  • 请回复@mkl no。
  • @DanCornilescu Ty 发表评论,但我不要求空指针异常。我的意思是为什么当我传递字节数组时图像为空。
  • 请分享imageInBase64EncodedString的值;否则我们无法回答您的问题。

标签: java pdf itext


【解决方案1】:

问题很可能是您传入的字符串值,因为您很可能会遇到值格式错误的异常。

我已经尝试了您的示例,使用来自 PasteBin (http://pastebin.com/bfc1E1NV) 的 BASE64 字符串示例,有人非常友好地发布了该示例,并且成功地按照您提供的代码运行了脚本。

ItextPdf 示例

截图 1

截图2(图片对象不为空)

org.apache.commons.codec.binary.Base64Example

【讨论】:

  • 您使用 ItextPdf 图像类。我正在使用 import org.apache.commons.codec.binary.Base64 来解码和获取字节值。但是在 image.scalePercent(15f) 我得到了 null...
  • 我已经修改了示例以包含您正在使用的库,并且我的测试仍然通过。你能提供给我你试图传入的字符串值吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 2013-08-07
  • 2019-12-02
  • 2011-08-29
  • 2011-11-25
  • 1970-01-01
相关资源
最近更新 更多