iText 文本和条形码之间的差距

Gap between text and barcode with iText

我正在使用库 iText-2.1.3 生成 Barcode128。这是我正在使用的代码:

private void createBarcode(String kodDokumentu, String idSadowka, String projekt) throws IOException, DocumentException
    {
        File barcodePdf = new File(pathToPdf);
        Files.deleteIfExists(barcodePdf.toPath());
        Document document = new Document();
        Rectangle size = new Rectangle(151,60);
        document.setMargins(5, 1, -6, 0);
        document.setPageSize(size);
        FileOutputStream fos = new FileOutputStream(pathToPdf);
        PdfWriter writer = PdfWriter.getInstance(document, fos);

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        Barcode barcode128 = new Barcode128();
        barcode128.setBarHeight(40);
        barcode128.setX(1.04f);
        barcode128.setCode("VL#"+kodDokumentu.toUpperCase());
        barcode128.setCodeType(Barcode.CODE128);
        Image code128Image = barcode128.createImageWithBarcode(cb, null, null);
        Font code = new Font(FontFamily.TIMES_ROMAN, 8, Font.NORMAL, BaseColor.BLACK);
        Paragraph p = new Paragraph("ID: "+idSadowka+",   Projekt: "+projekt.substring(0, 2), code);
        document.add(p);
        document.add(code128Image);
        document.close();
        fos.close();
    }

我想实现尽可能小的 h(看图片),如果 h=0.01 最好,因为我想为 ID: xxxxx, Projekt: xx 节省更多空间它更大,更容易被人类阅读。 首先(底部条码)我使用字体大小 8,然后(上部条码)我尝试将字体大小更改为 10,但是当我这样做时 h 比以前大。我知道字体大小与条形码和上面的文本之间的间隙有关,但是是否可以使用更大的字体大小并将这个间隙设置得非常小?

不确定它是否在您使用的 iText 版本中可用,但至少在 iText 5 上,您可以选择在段落上设置 "spacing after"。这正是您所需要的,即您在该段落下指定一个固定的 space,并且您在该段落之后添加到文档中的任何元素都将位于该 space.

p.setSpacingAfter(x)

其中 x 是您需要的 space,以用户单位或 "points" 为单位。