如何使用Java的iText库将Webp图片插入PDF?遇无法识别格式报错如何解决?
问题原因
你遇到的报错是因为当前使用的iText版本原生不支持WebP格式:
- iText 5及更早版本没有内置WebP解码能力,无法直接识别WebP格式的字节数组,调用
Image.getInstance()时就会抛出The byte array is not a recognized imageformat异常 - iText 7需额外引入对应WebP支持扩展包,才可直接加载WebP格式图片
解决方案
方案1:沿用当前iText 5版本,先转格式再加载
引入支持WebP解码的第三方依赖(比如webp-imageio),先将WebP字节数组转换为iText 5支持的PNG/JPG格式字节数组,再传入Image.getInstance()方法。
参考修改后的代码:
public byte[] generatePdfById(String uuid) { try { log.info("Generate document for id {} ", uuid); PointDao ptDao = pointRepository.getById(uuid); Document document = new Document(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PdfWriter.getInstance(document, outputStream); List<byte[]> images = storedService.getBucketZipByKey(ptDao.getImageZip(), "images"); byte[] firstImage = images.get(0); // 新增WebP转PNG逻辑 ByteArrayInputStream bais = new ByteArrayInputStream(firstImage); BufferedImage bufferedImage = ImageIO.read(bais); ByteArrayOutputStream pngBaos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", pngBaos); byte[] pngBytes = pngBaos.toByteArray(); Image image = Image.getInstance(pngBytes); document.open(); document.add(image); document.close(); byte[] bytes = outputStream.toByteArray(); return bytes; } catch (Exception e) { throw new PtRuntimeException(e.getMessage()); } }
注:如果ImageIO默认无法识别WebP,需提前注册WebP的ImageIO解码插件。
方案2:升级到iText 7版本,引入WebP扩展支持
升级iText核心依赖到7.x版本,同时引入官方WebP支持模块,可直接调用对应API加载WebP格式字节数组,无需额外格式转换。
内容的提问来源于stack exchange,提问作者cht_usr
相关产品推荐
相关产品推荐

