Add rectangle as inline-element with iText

2019-06-05 07:13发布

问题:

How do I add a rectangle (or other graphical elements) as inline-elements to an iText PDF?

Example code of what I'm trying to achieve:

foreach (Row r in entrylist)
{
    p = new Paragraph();
    p.IndentationLeft = 10;
    p.SpacingBefore = 10;
    p.SpacingAfter = 10;

    p.Add(new Rectangle(0, 0, 10, 10));  <<<<<<<<< THAT ONE FAILS
    p.Add(new Paragraph(r.GetString("caption"), tahoma12b));
    p.Add(new Paragraph(r.GetString("description"), tahoma12));
    ((Paragraph)p[1]).IndentationLeft = 10;
    doc.Add(p);
}

It's something like a column of text-blocks, of which each of them have (only a printed) checkbox.

I've tried various things with DirectContent, but it requires me to provide absolute X and Y values. Which I simply don't have. The elements should be printed at the current position, wherever that may be.

Any clues?

回答1:

You need a Chunk for which you've defined a generic tag. For instance, in this example listing a number of movies, a snippet of pellicule is drawn around the year a movie was produced and an ellipse was drawn in the background of the link to IMDB.

If you look at the MovieYears example, you'll find out how to use the PdfPageEvent interface and its onGenericTag() method. You're right that you can't add a Rectangle to a Paragraph (IMHO that wouldn't make much sense). As you indicate, you need to draw the rectangle to the direct content, and you get the coordinates of a Chunk by using the setGenericTag() method. As soon as the Chunk is drawn on the page, its coordinates will be passed to the onGenericTag() method.



标签: itext