Java如何使用IText向PDF中插入SVG

    前边了解到可以使用IText生成PDF文件,但是IText本身不直接支持插入SVG,所以我们要进行一次格式准换,现将SVG文件转换成Image,然后插入Image,达到插入SVG的效果。

    将SVG转换成Image我使用的是batik

    官网:https://xmlgraphics.apache.org/batik/

    Maven包:https://mvnrepository.com/artifact/org.apache.xmlgraphics

    我们只是做格式转换的话,只引入下边的依赖就可以,相关的jar包都包括了

<!-- batik -->
<dependency>
     <groupId>org.apache.xmlgraphics</groupId>
     <artifactId>batik-codec</artifactId>
     <version>1.12</version>
</dependency>

示例代码:

           try(InputStream is = file.getObjectContent()){
                byte[] bytes;
                if("image/svg+xml".equals(file.getObjectMetadata().getContentType())){
                    PNGTranscoder t = new PNGTranscoder();
                    TranscoderInput input = new TranscoderInput(is);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    TranscoderOutput output = new TranscoderOutput(out);
                    t.transcode(input, output);
                    out.flush();
                    bytes = out.toByteArray();
                }else{
                    bytes = StreamUtil.inputStreamToByte(is);
                }
                Image image = Image.getInstance(bytes);
                image.setAlignment(Element.ALIGN_CENTER);
                PdfPCell cell = new PdfPCell(image, true);
                cell.setBorderColor(BaseColor.GRAY);
                cell.setFixedHeight(20);
                cell.setPaddingTop(2);
                cell.setPaddingBottom(2);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
            }catch (Exception e){
                logger.error("[get material thumb error]: ",e);
                throw new RuntimeException(e);
            }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值