itextpdf生成条形码下方数字怎么和宽度一样

itextpdf生成条形码下方数字怎么和宽度一样,没有找到设置下方字体的方法

img


要求如下

img

要让条形码下方的数字与条形码的宽度相同,您需要对数字的字体大小和位置进行调整。以下是一个使用iText 7库创建条形码的示例,其中数字的字体大小已经调整为与条形码的宽度相同:

Barcode128 barcode = new Barcode128(document);
barcode.setCode("123456789");
barcode.setFont(null);
barcode.setSize(null);
Image code128Image = barcode.createImageWithBarcode(writer.getDirectContent(), BaseColor.BLACK, BaseColor.BLACK);
document.add(code128Image);

Chunk chunk = new Chunk("123456789", new Font(Font.FontFamily.HELVETICA, barcode.getBarHeight(), Font.NORMAL));
Phrase phrase = new Phrase(chunk);
float x = (code128Image.getWidth() - phrase.getWidth()) / 2;
float y = code128Image.getAbsoluteY() - barcode.getBarHeight();
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, phrase, x, y, 0);


在这个示例中,我们首先创建了条形码,并将它添加到PDF文档中。然后,我们创建一个Chunk对象,用于表示数字文本,并将其包装在一个Phrase对象中。我们还计算了数字的水平和垂直位置,使其位于条形码下方,并使用ColumnText.showTextAligned()方法将数字添加到PDF文档中。

注意,barcode.getBarHeight()方法返回条形码的高度,因此我们将字体大小设置为该高度以确保数字与条形码的宽度相同。如果您需要使用不同的字体或位置,请相应地进行调整。

该回答引用GPTᴼᴾᴱᴺᴬᴵ
在iTextPDF中生成条形码时,可以使用Barcode对象来创建条形码。要在条形码下方添加数字,可以使用Barcode对象的setBaseline()方法设置文本基线位置,并将文本添加到PdfTemplate中,最后将模板添加到PdfContentByte中。

下面是一个例子:

BarcodeEAN barcode = new BarcodeEAN();
barcode.setCode("123456789012");
barcode.setType(Barcode.EAN13);

PdfContentByte canvas = writer.getDirectContent();
float baseline = barcode.getBaseline(-2);
float size = barcode.getSize() / barcode.getCode().length();
PdfTemplate textTemplate = canvas.createTemplate(size, size);
textTemplate.beginText();
textTemplate.setFontAndSize(BaseFont.createFont(), size);
textTemplate.showTextAligned(Element.ALIGN_CENTER, "123456789012", size / 2, baseline, 0);
textTemplate.endText();

barcode.setTemplate(textTemplate);

document.add(barcode.createImageWithBarcode(canvas, null, null));


在这个例子中,我们使用BarcodeEAN对象创建一个EAN13类型的条形码。我们使用getBaseline(-2)方法获取文本的基线位置,然后创建一个大小与条形码宽度相同的PdfTemplate对象,并将文本添加到该模板中。最后,我们将该模板设置为条形码的模板,使用createImageWithBarcode()方法创建条形码图像并添加到PDF文档中。
·
注意,上面的代码中使用的是默认字体,如果需要使用自定义字体,可以使用BaseFont.createFont()方法来创建字体对象。另外,showTextAligned()方法中的Element.ALIGN_CENTER参数表示将文本水平居中对齐,可以根据需要修改。