Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iText - Adding external image using Chunk

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?

like image 791
caca Avatar asked Jun 20 '12 11:06

caca


1 Answers

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.

like image 92
Pier Luigi Avatar answered Sep 26 '22 21:09

Pier Luigi