Search code examples
javaitextbarcode

Gap between text and barcode with iText


I am generate Barcode128 with library iText-2.1.3. This is code which I am using:

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();
    }

I want to achive as small h (take a look at image) as it is possible, best if h=0.01 because I want to save more place for ID: xxxxx, Projekt: xx to make it bigger and easier to read by human. First (bottom barcode) I used font size 8, then (upper barcode) I tried to change font size to 10 but when I did it h is bigger than previous. I know that font size is connected with gap between barcode and text above it but is it possible to use bigger font size and set this gap really small?

enter image description here


Solution

  • Not sure if it's available in the version of iText you use, but on iText 5 at least, you have the option to set the "spacing after" on Paragraphs. It would be exactly what you need, i.e. you specify a fixed space under the paragraph, and any elements you add to the document after that paragraph, will go under that space.

    p.setSpacingAfter(x)
    

    Where x being the space you need, in user units or "points".