前边了解到可以使用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);
}