Search code examples
javaitextitextpdf

Itextpdf : set image in middle of text


I have a text in paragraph I want set an image in the middle of text :

public void createPdf(String dest, String imgSource) throws IOException, DocumentException {
    Document doc = new Document ();
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(dest));
    doc.open ();
    Paragraph p = new Paragraph();
    Image image1 = Image.getInstance(imgSource);
    p.add(new Chunk("This is my photo : "));
    p.add (image1);
    p.add(new Chunk(" so beautifull :)"));
    doc.add(p);
    doc.close();
}

it is a small image (width=100, height=50), but my image is sit in second line. Is it possible to set like this : "This is my photo : [IMAGE] so beautifull :)"


Solution

  • If you wrap the Image object in a Chunk, you can use it as an inline element:

    Paragraph p = new Paragraph();
    Image image1 = Image.getInstance(imgSource);
    p.add(new Chunk("This is my photo : "));
    p.add (new Chunk(image1, 0, 0, true));
    p.add(new Chunk(" so beautifull :)"));
    

    The 2nd and 3rd parameter of that Chunk constructor can be used to offset the image horizontally and vertically.