我目前正在使用itextPdf库来生成PDF文件。
为了设置图像,我使用了itextpdf.com的this solution 现在我想在模式拼接中将PdfPCell中的小尺寸图像设置为背景:如果单元格有3 x ImageSize,则在PDF中我会在单元格中重复我的图像
我怎么做?
这是我的例子
public class ImageBackgroundEvent implements PdfPCellEvent {
protected Image image;
protected boolean mosaic;
protected boolean full;
public ImageBackgroundEvent(Image image, boolean mosaic, boolean full) {
this.image = image;
this.mosaic = mosaic;
this.full = full;
}
public void cellLayout(PdfPCell cell, Rectangle position,
PdfContentByte[] canvases) {
try {
PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS];
if(full){
cell.setImage(image);
}
else if(mosaic){
float imgWidth = image.getWidth();
float imgHeight = image.getHeight();
float cellWidth = cell.getWidth();
float cellHeight = cell.getHeight();
if(imgHeight < cellHeight && imgWidth < cellWidth){
PdfPatternPainter pattern = cb.createPattern(imgWidth, imgHeight);
pattern.addImage(image);
pattern.setPatternMatrix(-0.5f, 0f, 0f, 0.5f, 0f, 0f);
cb.setPatternFill(pattern);
//cb.ellipse(180, 408, 450, 534);
cb.fillStroke();
} else{
image.scaleAbsolute(position);
image.setAbsolutePosition(position.getLeft(), position.getBottom());
cb.addImage(image);
}
} else{
image.scaleAbsolute(position);
image.setAbsolutePosition(position.getLeft(), position.getBottom());
cb.addImage(image);
}
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
}
}
答案 0 :(得分:1)
请查看TiledBackgroundColor示例。它需要一个灯泡的图像,并用它来定义图案颜色:
PdfContentByte canvas = writer.getDirectContent();
Image image = Image.getInstance(IMG);
PdfPatternPainter img_pattern = canvas.createPattern(
image.getScaledWidth(), image.getScaledHeight());
image.setAbsolutePosition(0, 0);
img_pattern.addImage(image);
BaseColor color = new PatternColor(img_pattern);
现在,您可以将该颜色用于单元格的背景:
PdfPCell cell = new PdfPCell();
cell.setFixedHeight(60);
cell.setBackgroundColor(color);
table.addCell(cell);
结果如下所示:tiled_patterncolor.pdf
或者您可以在单元格事件中添加图像,如TiledBackground示例中所示。这个例子是在回答问题iTextSharp. Why cell background image is rotated 90 degrees clockwise?
时写的我已就此示例撰写了一个变体:TiledBackgroundColor2
事件如下所示:
class TiledImageBackground implements PdfPCellEvent {
protected Image image;
public TiledImageBackground(Image image) {
this.image = image;
}
public void cellLayout(PdfPCell cell, Rectangle position,
PdfContentByte[] canvases) {
try {
PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS];
image.scaleToFit(10000000, position.getHeight());
float x = position.getLeft();
float y = position.getBottom();
while (x + image.getScaledWidth() < position.getRight()) {
image.setAbsolutePosition(x, y);
cb.addImage(image);
x += image.getScaledWidth();
}
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
}
}
如您所见,我并不关心图像的实际尺寸。我以适合单元格高度的方式缩放图像。我也没有使用图案颜色。我只是添加图像,因为它适合单元格的宽度。
这是我向单元格声明事件的方式:
PdfPCell cell = new PdfPCell();
Image image = Image.getInstance(IMG);
cell.setCellEvent(new TiledImageBackground(image));
结果如下:
根据您的具体要求,可能会有很多变化。