问题描述
如何在 iText 7 中制作表格,其中单元格的内部没有任何间距、填充或边距。当我将图像放入单元格时,它需要将单元格填充到 100%,在没有任何空间的情况下触摸边框。
我尝试将其添加到我的 Cell:
Cell qrImageCell = new Cell();
qrImageCell.setMargin(0f);
qrImageCell.setPadding(0f);
qrImageCell.setHeight(44f);
qrImageCell.add(barcodeImage.setMargins(0f,0f,0f).setPadding(0f));
我也尝试在表格中设置它:
table.setPadding(0f);
table.setMargin(0f);
但无论我尝试什么,在二维码和边框之间总会有一个白色的矩形区域(仅供参考:一旦它起作用,我当然会删除边框。
解决方法
使用 iText 7.1.15 进行测试
使用这张图片:
还有这段代码:
Table table = new Table(1);
Image barcodeImage = new Image(ImageDataFactory.create("image.png"));
Cell qrImageCell = new Cell();
qrImageCell.setBorder(new SolidBorder(ColorConstants.RED,2));
qrImageCell.setPadding(0f);
qrImageCell.add(barcodeImage);
table.addCell(qrImageCell);
doc.add(table);
结果输出为:
潜在原因
高度不正确
您的代码中有 qrImageCell.setHeight(44f)
。也许该高度与您的图像高度不正确对应。但这不太可能是问题所在,因为它不会增加单元格的宽度。
其他细胞的影响
将上面测试的表格做成一个2列的表格,并添加几个单元格,可以看出同一行同一列的单元格的大小会对单元格的大小产生影响。
table.addCell(new Cell().add(new Paragraph("cell (1,2)")).setHeight(300));
table.addCell(new Cell().add(new Paragraph("cell (2,1)")).setWidth(300));
table.addCell(new Cell().add(new Paragraph("cell (2,2)")));
这也不太可能是问题所在,因为在您的输出中,图像以单元格为中心。
没有空格
也许白色的“边距”只是条形码图像的一部分。在这种情况下,没有任何间距、边距或填充,但在视觉上看起来如此。
验证您的输入图像或为单元格设置背景颜色,以便您可以验证白色区域是图像的一部分还是单元格的一部分:qrImageCell.setBackgroundColor(ColorConstants.GREEN)
最后,背景色技巧对我帮助很大。最后,由于某种原因也由 iText7 生成的 QR 图像在其周围有一个白色边框。它由以下代码生成:
BarcodeQRCode qrCode = new BarcodeQRCode(text);
PdfFormXObject barcodeObject = qrCode.createFormXObject(ColorConstants.BLACK,pdfDoc);
Image barcodeImage = new Image(barcodeObject).setPadding(0f).scaleAbsolute(44f,44f)
但确实将填充设置为“0f”会删除单元格中的任何填充。只需要找出是否有可能删除 QR 码周围的边框。