IText生成PDF添加图片非后期合成方式
网上有很多方法给PDF添加图片,都是PDF已经生成好了,再合成一个图片上去。这样很麻烦,要计算图片的位置。
后来发现了这个方法,可以直接在PdfPcell里添加一个Image,这样就不用计算位置和大小了。直接填充满cell就可以当背景了。
首先要实现PdfPCellEvent接口,如下:
class ImageBackgroundEvent implements PdfPCellEvent { protected Image image; public ImageBackgroundEvent(Image image) { this.image = image; } public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { try { PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS]; image.scaleAbsolute(position); image.setAbsolutePosition(position.getLeft(), position.getBottom()); cb.addImage(image); } catch (DocumentException e) { throw new ExceptionConverter(e); } }
然后在想要显示图片的Cell里添加这个事件就可以
Image image = Image.getInstance("imgPath");
cell.setCellEvent(new ImageBackgroundEvent(image));
这样在PDF生成的时候就会把图片带进去了,而不用完成之后再去追加了。

浙公网安备 33010602011771号