iText - Adding external image using Chunk

17,418

The behaviour you described is because in the second code snippet the Paragraph doesn't adjust its leading, but adjust its width. If in the second snippet you add the line

p.add("Hello world 1")

just before

p.add(img)

you'll see the string "Hello world 1" on the left and a little bit above the string "Hello Worlddd!". If you output the leading of p (System.out.println(p.getLeading()) you can see it's a low number (typically 16) and not the height of the image.

In the first example you use the chunk constructor with 4 arguments

new Chunk(img, 0, 0, true)

with the last (true) saying to adjust the leading, so it print as you expected.

Share:
17,418
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am new to iText and faced with a real interesting case about adding external images to a paragraph. Here is the thing:

    Document document = new Document();  
    PdfWriter.getInstance(document, new FileOutputStream("out2.pdf"));  
    document.open();  
    Paragraph p = new Paragraph();  
    Image img = Image.getInstance("blablabla.jpg");  
    img.setAlignment(Image.LEFT| Image.TEXTWRAP);  
    // Notice the image added to the Paragraph through a Chunk
    p.add(new Chunk(img2, 0, 0, true));  
    document.add(p);  
    Paragraph p2 = new Paragraph("Hello Worlddd!");  
    document.add(p2);
    

    gives me the picture and "Hello Worlddd!" string below. However,

    Document document = new Document();  
    PdfWriter.getInstance(document, new FileOutputStream("out2.pdf"));  
    document.open();  
    Paragraph p = new Paragraph();  
    Image img = Image.getInstance("blablabla.jpg");  
    img.setAlignment(Image.LEFT| Image.TEXTWRAP);  
    // Notice the image added directly to the Paragraph
    p.add(img);
    document.add(p);  
    Paragraph p2 = new Paragraph("Hello Worlddd!");  
    document.add(p2);
    

    gives me the picture and string "Hello worlddd!" located on the right hand side of the picture and one line above it.

    What is the logic behind that difference?